Creating a "Hello World" Fastify application with a Docker boilerplate is a great way to get started with developing containerized Node.js applications. Below are the steps to create a simple Fastify application and dockerize it.
Step 1: Initialize a Node.js Project
Create a new directory for your project and initialize it with npm or yarn.
mkdir fastify-hello-world
cd fastify-hello-world
npm init -y
Step 2: Install Fastify
Install Fastify using npm.
npm install fastify
Step 3: Create the Fastify Server
Create an index.js file with the following content:
// index.js
const fastify = require('fastify')({ logger: true });
fastify.get('/', async (request, reply) => {
return { hello: 'world' };
});
const start = async () => {
try {
await fastify.listen(3000);
console.log(`Server listening on ${fastify.server.address().port}`);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
Step 4: Test the Application Locally
Run the Fastify application locally to make sure it works:
node index.js
Navigate to http://localhost:3000 in your web browser or use curl to test the API endpoint.
curl http://localhost:3000
Step 5: Create a Dockerfile
Create a Dockerfile in the root of your project with the following content:
# Use the official Node.js 16 image.
# https://hub.docker.com/_/node
FROM node:16
# Create and change to the app directory.
WORKDIR /usr/src/app
# Copy application dependency manifests to the container image.
# A wildcard is used to ensure both package.json AND package-lock.json are copied.
# Copying this separately prevents re-running npm install on every code change.
COPY package*.json ./
# Install production dependencies.
RUN npm install --only=production
# Copy local code to the container image.
COPY . .
# Bind the port that the app will run on.
EXPOSE 3000
# Run the web service on container startup.
CMD [ "node", "index.js" ]
Step 6: Build