Does Fastify Work With Docker?
Fastify works excellently with Docker; the framework's low overhead and stateless design make it ideal for containerized deployments.
Quick Facts
How Fastify Works With Docker
Fastify integrates seamlessly with Docker because of its lightweight footprint, fast startup time, and stateless architecture. You create a Dockerfile that installs Node.js dependencies and exposes the port Fastify listens on, then Docker handles process isolation and resource constraints. The combination excels in microservices architectures where multiple Fastify containers can be orchestrated with Docker Compose or Kubernetes. Since Fastify has minimal memory overhead compared to Express or Hapi, it packs efficiently into containers and scales horizontally without bloating images. The framework's plugin system also works well with container environment variables for configuration injection, letting you customize behavior across development, staging, and production deployments without rebuilding images.
Best Use Cases
Quick Setup
npm init -y && npm install fastify# app.js
const fastify = require('fastify')({ logger: true });
fastify.get('/health', async (req, reply) => {
return { status: 'ok' };
});
const start = async () => {
try {
await fastify.listen({ port: 3000, host: '0.0.0.0' });
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
# Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]
# Build and run
# docker build -t fastify-app .
# docker run -p 3000:3000 fastify-appKnown Issues & Gotchas
Fastify listens on localhost (127.0.0.1) by default, which prevents external connections inside containers
Fix: Explicitly bind to 0.0.0.0 when calling fastify.listen(), or use the host option: await app.listen({ port: 3000, host: '0.0.0.0' })
Node process doesn't handle SIGTERM gracefully, causing slow container shutdowns
Fix: Use app.close() in a SIGTERM handler: process.on('SIGTERM', () => app.close())
Multi-stage builds can cause version mismatches if Node LTS versions differ between build and runtime stages
Fix: Use the same base image tag (e.g., node:18-alpine) in both build and runtime stages
Environment variables defined in .env files aren't automatically loaded in Docker containers
Fix: Use docker run -e VAR=value or pass an .env file with --env-file flag, or use a package like dotenv in your startup code
Alternatives
- •Express with Docker - more mature ecosystem but higher overhead and slower startup
- •Hapi with Docker - more feature-rich but heavier, better for monolithic applications
- •Nest.js with Docker - opinionated framework with built-in dependency injection, steeper learning curve
Resources
Related Compatibility Guides
Explore more compatibility guides