> Docker is an open platform for developing, shipping, and running applications.
In other words, It enables developers to package applications into containers—standardized executable components combining application source code with the operating system (OS) libraries and dependencies required to run that code in any environment.
Lets look at practical example on how we can use Docker to ship our NodeJs app and all the development dependencies using Docker.
Prerequisite
🎯 Docker download
🎯 NodeJs download
⚙️ Setup
Make sure your docker daemon is active. Click on the Docker Desktop Icon to start the Docker engine.
Check if docker is installed on your PC correctly
Run this command
: docker --version
Result
Dockerize NodeJS App
Let initiate our NodeJs Project using the npm init -y
command
Install Project Dependencies
Install Express using npm i express
, create index.js file and create a NodeJs Server.
Let's test our app
For simplicity sake, i edited the package.json
file and fired the app using npm start
Dockerizing your NodeJs App
Create a Dockerfile and Paste the below code
Code explanation
1. The FROM command tells Docker to use the node:14.17.0-alpine image as the base image for the Dockerfile.
2. WORKDIR /app tells Docker to set the working directory for the container to /app.
3. ADD package*.json ./ tells Docker to copy the package.json file into the container.
4. RUN npm install tells Docker to run npm install inside the container.
5. ADD index.js ./ tells Docker to copy the index.js file into the container.
6. EXPOSE 5050 tells Docker to expose the port 5050 on the container.
7. CMD [ "node", "index.js"] tells Docker to run node index.js inside the container.
Let's Build our app
The dockerized-app
is the name i gave my Docker Image that i want to build. You can use any descriptive name of your choice. The .
is referring to the current folder.
Let's check our built image
Next, we run our container from the images
Explanation:
1. The -d flag is used to run the container in the background
2. The -p flag is used to set the port that the container will listen on.
3. The port number 4001 is your localhost port and 5050 the port that you are making the request to i.e the Container port that we exposed earlier.
4. The name of the container is node-api
5. The dockerized-app image is the name of the image that you are going to run.
`
Check all running containers
Lets test our exposed port of our running instance on browser
Inspect your running instance
Stop a running container
Restart a running container
Remove the running container (force remove)
Conclusion
I hope this post was helpful.
Top comments (2)
Issue resolved?