Update: Iāve written another part to this story, introducing Multi-Stage builds into this Dockerfile, to reduce the image size, check it out: Fastify + Distroless + Multi-Stage Builds = š¤Æ
In the previous blog post, we described how to run a simple āhello worldā HTTP server using Fastify inside a Docker container in Node.js. In this short second part, we will update the Dockerfile to use a distroless Node.js base image instead of the official Node.js image.
Distroless images are a type of container image that does not include a Linux distribution or package manager. This can help reduce the size of the image and improve security by reducing the attack surface of the container.
Prerequisites
- Docker installed on your system.
- Basic knowledge of Docker and building Docker images.
- Implemented Fastify + Docker
Create a new Dockerfile
First, create a new file called Dockerfile.distroless
in the root of your project directory, or replace the existing Dockerfile
. This file will contain the instructions for building your Docker image using a distroless base image.
FROM gcr.io/distroless/nodejs:16
ENV ADDRESS=0.0.0.0 PORT=3000
WORKDIR /app
COPY package.json .
RUN npm install --production
COPY . .
CMD ["node", "index.js"]
This Dockerfile starts with the gcr.io/distroless/nodejs:16
base image, sets the working directory to /app
, copies the package.json
file to the working directory, installs only production dependencies using npm, copies the rest of the files to the working directory, and sets the default command to run the node index.js
command.
Note: weāre installing only production dependencies here, as we donāt need development dependencies in our production environment.
Build the Docker image
Now that you have created the Dockerfile.distroless
, you can use it to build a Docker image. Run the following command in your terminal:
docker build -f Dockerfile.distroless -t fastify-distroless .
This command tells Docker to build an image using the instructions in the Dockerfile.distroless
and tag it with the name fastify-distroless
.
Run the Docker container
Finally, you can run the Docker container using the distroless-based image you just built. Run the following command in your terminal:
docker run -p 3000:3000 fastify-distroless
This command tells Docker to run a container using the fastify-distroless
image and map port 3000
inside the container to port 3000
on your local machine.
Test the server
You can now test your āhello worldā server by opening a web browser and navigating to http://localhost:3000. You should see a JSON response containing the message āHello world!ā.
Congratulations! You have successfully built and run a Fastify HTTP server inside a Docker container using a distroless Node.js base image. By using a distroless base image, you have reduced the size of the container and improved its security by minimizing the attack surface.