How to Dockerize a JavaScript Application
In this lesson, you will learn how to Dockerize a simple JavaScript project. The project is a simple Express 5 Todo API that I have already built.
Here’s the Postman result of the API:
If you want to follow along with creating the project, you can read through Express 5: The Ultimate Guide for the step-by-step guide or you can clone the repository from GitHub.
Create a Dockerfile
Create a Dockerfile
in the root directory of the Express 5 Todo API project and add the following script:
# Create from a base image
FROM node:16.17.0-alpine
# Set working directory
WORKDIR /usr/src/app
# Copy Package.json files
COPY package*.json ./
# Install production-only dependencies
RUN npm ci --production
# Copy all files now
COPY . .
# Expose port 3000 to your host machine
EXPOSE 3000
# Run Npm Start command
CMD [ "npm", 'start']
Look at the comments in the script for the explanation.
After creating your Dockerfile
and adding the necessary instructions to create a container, the next step is to build the image.
Build the image
We will use the docker build
or docker image build
command we explored above to build the image. Open your terminal and type in the following command in the directory where the Dockerfile
is located:
docker build -t my-express-app .
When you enter the command, Docker will start pulling the base image and setting up your container for you. You will see a result similar to the one below if everything is successful.
The next step is to run the container that we’ve created.
Running the image
As we have already explored, you can use the Run
command to run any image. Type the following command into your terminal to run your image:
docker run --name my-express-app-container -it -p 4000:3000 my-express-app
If this works, you should be greeted with a screenshot as shown below:
As you can see, inside the container the post is 3000
but have mapped that point to 4000
in our host system. So to preview the API in the browser or access it with Postman, we will use port localhost:4000
.
If everything works properly, if you visit localhost:4000
you should see the result similar to the one below:
We have practically Dockerised a simple JavaScript application. We have created a Docker image using Dockerfile, build and run it into a container
Furthermore, you can practice all the commands we have listed above to master each of them because they will become handy as you build more complex applications.
Next, let’s look at how to Dockerize a full-stack application that includes a front end, a backend, and a database. This will help us understand how to Dockerize complex applications using Docker Compose.