Dockerize Gatsby Project

Published on March 2nd, 2024

It is good practice to containerize one's applications. It makes developing projects on different machines easier and facilitates their deployment.

This is not only true for your backend code but especially true for your Gatsby code, even if you are the only one working on it and don't plan on changing machines. Something I've noticed with JavaScript-based projects is that when you come back to them a few months later, nothing works anymore! Today was particularly bad; running my simple Gatsby blog made my computer crash again and again. This had to stop.

That might not be a problem for some people if they are working 24/7 on the same codebase. However, when you have tens of projects like me and you go back and forth, you want to waste as little time as possible making the dev server work again.

Containerize a Gatsby project

Here is a Gatsby-friendly Dockerfile:

# Use an official Node runtime as a parent image
FROM node:14

# Set the working directory in the container
WORKDIR /usr/src/app

# Copy package.json and package-lock.json (or yarn.lock) to the working directory
COPY package*.json ./

# Install dependencies
RUN npm install

# Bundle app source inside the Docker image
COPY . .

# Make port 8001 available to the world outside this container

# Define environment variable
ENV NODE_ENV=development

# Run gatsby develop on container start
CMD ["npm", "run", "develop"]

And we also need a docker-compose.yml, mainly to make hot-reloading work:

version: '3.8'
    build: .
      - .:/usr/src/app
      - /usr/src/app/node_modules
      - "8001:8001"
      NODE_ENV: development
    command: npm run develop

Start the app:

docker-compose up --build 

Thank you for reading.