Dockerizing Your Node.js Application
Step 1: Setting Up the Environment
Clone the Repository
git clone https://github.com/docker/getting-started-app.git
cd getting-started-app/
Sample application to dockerize. We will use a simple to-do list application available on GitHub.
buymeacoffee ☕ 👈 Click the link
Create a Dockerfile
Create a new file named Dockerfile in the root of your project directory.
touch Dockerfile
Open the Dockerfile in a text editor and add the following content:
Use an official Node runtime as a parent imageFROM node:18-alpine
Set the working directory in the containerWORKDIR /app
Copy the current directory contents into the container at /appCOPY . /app
Install any needed packages specified in package.jsonRUN yarn install --production
Make port 3000 available to the world outside this containerEXPOSE 3005
Define environment variableENV NAME World
Run app.py when the container launchesCMD ['node', "src/index.js"]
Step 2: Building the Docker Image
With the Dockerfile in place, we can now build our Docker image.
docker build -t day02-todo .
Build the Docker image and tag it as day02-todo.
You can verify the image by running the docker images
command:
Create a public repository on “hub.docker.com” and push the image to remote repo.
docker login
docker tag local-image:latest username/new-reponame:tagname
docker tag day02-todo:latest ibrahimsi/test-repo:latest
docker images
docker push username/new-reponame:tagname
To pull the image to another environment , you can use below command
docker push username/new-reponame:tagname
docker push ibrahimsi/test-repo:latest
Check the docker hub
Step 3: Running the Docker Container
Pull the repository
docker pull ibrahimsi/test-repo:latest
Upto date latest image
Our Docker image, we can run it as a container.
docker run -dp 3005:3005 ibrahimsi/test-repo:latest
docker ps
This command will run the container in detached mode and map port 3005 on the host to port 3005 in the container.
Finally access the localhost:3005 → See the To Do app page
To enter(exec) into the container, use the below command
docker exec -it 1767fe55365853ce085f6fdaee5bfb5c34e673ed4eb9e /bin/sh
Thank you 🙏 for taking the time to read our blog.