Topics Production Fastify Deployment & Production
intermediate 14 min read

Deployment & Production

Deploy Fastify with PM2, Docker, environment configuration, and production best practices.

Production Deployment

// Environment configuration\nconst app = Fastify({\n  logger: {\n    level: process.env.LOG_LEVEL || 'info',\n    // In production, use JSON logs (no pino-pretty)\n    ...(process.env.NODE_ENV === 'production'\n      ? {}\n      : { transport: { target: 'pino-pretty' } }),\n  },\n  trustProxy: process.env.NODE_ENV === 'production',\n});\n\n// PM2 ecosystem.config.js\n// module.exports = {\n//   apps: [{\n//     name: 'fastify-api',\n//     script: 'app.js',\n//     instances: 'max',\n//     exec_mode: 'cluster',\n//     env: {\n//       NODE_ENV: 'production',\n//       PORT: 3000,\n//     },\n//     max_memory_restart: '500M',\n//   }]\n// };\n\n// Dockerfile\n// FROM node:20-alpine\n// WORKDIR /app\n// COPY package*.json ./\n// RUN npm ci --only=production\n// COPY . .\n// EXPOSE 3000\n// CMD [\"node\", \"app.js\"]\n\n// Listen on port and host\nconst start = async () => {\n  try {\n    await app.listen({\n      port: process.env.PORT || 3000,\n      host: process.env.HOST || '0.0.0.0',\n    });\n    app.log.info(`Server running on port ${process.env.PORT || 3000}`);\n  } catch (err) {\n    app.log.fatal(err);\n    process.exit(1);\n  }\n};\n\nstart();

Examples

const Fastify = require('fastify');

// Production-ready configuration
const app = Fastify({
  logger: {
    level: process.env.LOG_LEVEL || 'info',
    ...(process.env.NODE_ENV === 'production'
      ? {} // JSON logs in production
      : { transport: { target: 'pino-pretty' } }),
  },
  trustProxy: true, // Trust nginx/reverse proxy headers
});

// Graceful shutdown
async function gracefulShutdown(signal) {
  app.log.info(`Received \${"$"}{signal}, shutting down gracefully...`);
  await app.close();
  process.exit(0);
}

process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));

// Config endpoint
app.get('/config', async () => ({
  env: process.env.NODE_ENV || 'development',
  version: process.env.APP_VERSION || '1.0.0',
  nodeVersion: process.version,
  platform: process.platform,
}));

app.get('/health', async () => ({ status: 'ok' }));

const start = async () => {
  const port = process.env.PORT || 3000;
  const host = process.env.HOST || '0.0.0.0';
  await app.listen({ port, host });
  app.log.info(`Server running on http://\${"$"}{host}:\${"$"}{port}`);
};

start();

Your Notes

Sign in to take notes for this lesson.

Quiz

Production Fastify Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.