Running a NodeJs server on Docker

Running a NodeJs server on Docker

Learn Docker

·

2 min read

Docker is an open source platform for developing, shipping, and running applications. It enables you to separate your applications from your infrastructure so you can deliver software quickly.

It provides the ability to package and run an application in a loosely isolated environment called a container.

As we go along you are going to learn how to create images and run it in a container. First you need to have docker installed locally, you can find the installation file here.

Creating your docker file

Create a file Dockerfile in the root folder of your project and from your favorite editor add the following commands:

FROM node:16

WORKDIR /app

COPY package.json /app

ENV PORT=3000

RUN npm install

EXPOSE 3000

CMD ["npm", "start"]
  • FROM node:16 tells docker to use the nodejs latest stable version (at the time of this writing).
  • WORKDIR /app is the folder that will hold the application inside the image.
  • COPY package.json /app copies the package.json file into the build.
  • ENV PORT=3000 sets an environment variable PORT.
  • RUN npm install runs the install command during the build.
  • EXPOSE 3000 exposes the port outside the docker network and indicates the port on which a container listens for connections else it will bind to a default port.
  • CMD ["npm", "start"] defines the command to run your app when the container is started.

Building the image

Open your project folder in command prompt and run the command:

docker build -t <a name of your chosen> .

and press enter. The -t flag helps tag a name to your image for easy identification. For example if you use

docker build -t myApp .

the myApp tag binds with your image to enable you easily identify or locate it. After building the image its time to run it.

Run the image

To the run the image execute the following command:

docker run -p 3000:3000 <image tag>

For example

docker run -p 3000:3000 myApp

and this will start app server on docker.

Conclusion

We have come to the end! It looks simple right? That's how it is though there's still more to learn. This will get you familiar with common commands used in docker when it comes to nodejs. For more studies and research visit the documentation on the NodeJs official website and the Docker website.