How to Create a Docker container for your NodeJs app 🐳

If you’ve ever wondered how to Dockerize and run your NodeJs app as a container, and never ever done it then you’ve landed at the right place
What you’ll be building
A NodeJs app Running on a Docker container on your local machine
Step 1
Initialising a NodeJs app with express
- cd into the folder you want to make your NodeJs app
- Run npm init -y
This will generate a package.json file for you

3. Now to install Express type 👇🏻
npm i express
and Press Enter or Return key
Express will now be installed as a dependency in your project
4. Now create a index.js file in your app directory with the following code
5. Your NodeJs express app is now ready. To run the app Open Terminal and cd into your project directory and type
node index.js

If you see server running message printed on terminal, tada your node app is now ready
Step 2
Time to dockerize it
In your project Directory create a file named Dockerfile without any extension and save it
Copy 👇🏻 these lines in Dockerfile
FROM node:alpine
this is the very first line of any Dockerfile and specifies the base image you are using to create your docker image, in our case we are usingnode:alpine
WORKDIR /var/www
this line specifies our current working directory. In our case we want our project to be in/var/www
, so we are saying docker that make our current working directory to/var/www
COPY package.json .
A self explanatory step we’re just simply copying our package.json file to our current working directoryRUN npm install
This step installs all our project’s dependencies in the docker containerCOPY . .
In the earlier step we copied only package.json to install dependencies only. Now as we have all the dependencies installed, we are copying all of our project’s files in to the containerEXPOSE 80
This step exposes Port 80 of our container for outer world to accessCMD [“node”, “index.js”]
And finally we’re running the app by running the node command
Build the Docker Image
we’re now one step closer to dockerizing our NodeJs app.
we have everything ready now. The last step that is left is just Build our Docker image from the Dockerfile and run it.
To build the image open your Terminal and cd into project folder
and run docker build -t image .
docker will now start building your image from Dockerfile
you’ll see a screen like 👇🏻 once it will finish building.

FINALLY it’s time to run our Docker container
Now run commanddocker run -p 80:80 image
and you’ll see message server running
Now go to your web browser and type localhost
and press Enter or Return

Congrats Your NodeJs project is Now dockerized 🎉🥳