
Creating a Node.js app inside a Docker container running Ubuntu is a straightforward way to ensure a consistent development environment. This guide will take you through the essential steps to set up and run your Node.js application within a Docker container.
1. Open terminal then go to folder where you will put your node js apps, then type this command
docker run --name proyekNode -it -v "$(pwd)":/proyekNode -p 80:80 ubuntu
That command will create a container with ubuntu OS, where you can start install necessary packages to build node js applications
2. Install node js
Type these commands to install node js
apt update
apt install nodejs npm
3. Open your work folder
Type this command to open your work folder
cd proyekNode
4. Create your first app
You can create new file with “app.js” as the file name and copy paste this code
const http = require("http");
const hostname = "0.0.0.0";
const port = 80;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Hello, World!\n");
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
5. Run your app
Now you can run your above code with the following command
node app.js
6. Open your app in browser
Now you can see the hello world message in your browser by open this URL
http://0.0.0.0:80/
By following these steps, you’ve successfully created and deployed a simple Node.js app in an Ubuntu Docker container. This setup ensures a consistent development environment and simplifies deployment, paving the way for more efficient and scalable applications. Happy coding!