Create a docker image of Node-Express API – Part I

How to build Node-Express project Docker Image.


Install dependencies

npm init -y
npm install express dotenv --save

.env

In the project route create a .env file to store the environment variables such as PORT. Let’s add the port

PORT=3000 

Run the Project

Save all the files and run the project for the first time.

node index.js

Visit the the API at http:\\localhost:3000

Make sure everything right, otherwise debug and fix error.

Preparing Image

In order to create a image , we need two files Dockerfile and .Dockerignore file.

Dockerfile

Prepare a Dockerfile in the project directory with following content (remember Dockerfile has no extension)

FROM node:latest
WORKDIR /app
ADD package*.json .
RUN npm install
ADD . .
CMD node index.js
  1. In the Line 1 we specify the base image we want to use.
  2. Using the WORKDIR specified the app directory where the file should kept in the container.
  3. Add all the package files (ADD)
  4. run install to download dependencies using RUN command
  5. The ADD option copies all content to working directory and specify where the Docker files stored.
  6. Finally run the Node command (CMD).

.Dockerignore file

These are files to be excluded from being copied to the container. For example you need not include node_modules because it can be get installed by the npm install RUN command.

Building the image

We are ready to try build image using build command with –tag. Do not use same tag more than once. Form within Project directory run the build command

 docker build -t user-api:latest .

The project path(`.`) tell the builder where the Dockerfile is located.

The above command will create an image ready for container. Check the image list. Got an error ? Let me know. After successful build try

docker image

It will list your image with ID.

In the next part we will use the User-API image to run a customer API container.

Author: Manoj

Developer and a self-learner, love to work with Reactjs, Angular, Node, Python and C#.Net

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.