Node JS Container
Last updated
Last updated
i. Clone this project:
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:
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:
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:
Next, we’re going to create a Docker container by running the created image and by using the command below:
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
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.
Then, execute into the container by using the container ID and list the files, as shown below: