Node JS Container

Running the Application without Docker

i. Clone this project:
1
git clone https://github.com/collins-b/blogpost.git
2
cd blogpost
Copied!
Run npm install, to install packages, then run npm start. Then visit http://localhost:3000, where you should see something similar to the below image:
Running the Application without Docker

Dockerizing the Application

We’re going to use the project you cloned above. Now, let’s see how to integrate Docker into your existing project.
i. In the root directory, create a file named Dockerfile, if the name does not exist. This is a text document that contains all the commands that a user could call on the command line to assemble an image.
ii. Populate the file with the following contents:
1
FROM node
2
ENV NPM_CONFIG_LOGLEVEL warn
3
RUN mkdir -p /usr/src/app
4
EXPOSE 3000
5
WORKDIR /usr/src/app
6
ADD package.json /usr/src/app/
7
RUN npm install --production
8
ADD . /usr/src/app/
9
ENTRYPOINT ["npm", "start"]
Copied!
The commands are explained below:
FROM
The base image for building a new image in our case is the node. This command must be on top of the Dockerfile.
ENV
- It defines an environment variable.
RUN
- This is used to execute a command during the build process of the docker image.
ADD
- Copies a file from the host machine to the new docker image.
ENTRYPOINT
- Defines the default command that will be executed when the container is running.
WORKDIR
- This is directive for ENTRYPOINT command to be executed.
EXPOSE
- Exposes a specified port on which the container will run.
Next, run docker build -t web-app . to build a Docker image. Don’t forget to include the period. You can tag your image with any name. Here, I have tagged web-app as shown in the command:
Docker build
Next, we’re going to create a Docker container by running the created image and by using the command below:
1
docker run -d -p 3000:3000 web-app
Copied!
This creates a writeable container layer over the specified image and then starts using the specified command.
I’m using -d flag to run the container in background and print container ID. -p specifies the port in this case and here I’m exposing port 3000.
Docker run
Docker run
Visit http://localhost:3000 to access the application on your favorite browser. Yes, now you have successfully dockerized the application!
Now is time to check the contents of the created container. This is to prove all the files are in the container.
List the running containers using the command docker ps.
Running container
Then, execute into the container by using the container ID and list the files, as shown below:
Container shell
Last modified 2yr ago
Copy link