Table of Contents
Developing and testing Fastify applications locally can be streamlined using Docker Compose. This approach ensures a consistent environment across different development setups, reducing the "it works on my machine" problem.
Why Use Docker Compose with Fastify?
Docker Compose allows you to define and run multi-container Docker applications. For Fastify projects, it simplifies managing dependencies like databases, caches, or other microservices needed during development and testing.
Setting Up Your Docker Compose Environment
Start by creating a docker-compose.yml file in your project directory. This file describes the services, networks, and volumes needed for your Fastify app.
Example Docker Compose File
Below is a basic example that includes a Fastify server and a PostgreSQL database:
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
volumes:
- ./:/app
environment:
- NODE_ENV=development
command: npm run dev
depends_on:
- db
db:
image: postgres:13
environment:
POSTGRES_USER: fastify_user
POSTGRES_PASSWORD: fastify_password
POSTGRES_DB: fastify_db
ports:
- "5432:5432"
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
Configuring Your Fastify Application
Ensure your Fastify app connects to the database using environment variables. Modify your database connection code to read from environment variables like POSTGRES_USER, POSTGRES_PASSWORD, and POSTGRES_DB.
Sample Connection Code
Here's a simple example using node-postgres:
const { Client } = require('pg');
const client = new Client({
user: process.env.POSTGRES_USER,
host: 'db',
database: process.env.POSTGRES_DB,
password: process.env.POSTGRES_PASSWORD,
port: 5432,
});
client.connect()
.then(() => console.log('Connected to database'))
.catch(err => console.error('Connection error', err));
Running and Testing Your Environment
Build and start your containers with:
docker-compose up --build
This command will build your Fastify app container and start both the app and database containers. You can access your app at http://localhost:3000.
To stop the environment, run:
docker-compose down
Advantages of Using Docker Compose
- Consistent development environment across team members
- Easy setup and teardown of complex environments
- Isolation of dependencies
- Simplifies testing with different database versions or configurations
Implementing Docker Compose in your Fastify development workflow enhances productivity and ensures your application behaves reliably across different environments.