Dockerize your Gatsby Projects

Published on March 2nd, 2024

Cover Image for Dockerize your Gatsby Projects

JavaScript-based projects tend to rot quickly. Very often, when I come back to them a few months later, nothing works. Today simply running my Gatsby blog after a few months made my MacBook Pro crash.

Like most programmers, I have many side projects, and I want to minimise the time spent making the dev server work again. So here is the Docker cure for that.

Containerize a Gatsby project

Dockerfile for Gatsby:

# 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
EXPOSE 8001

# Define environment variable
ENV NODE_ENV=development
ENV CHOKIDAR_USEPOLLING=1
ENV GATSBY_WEBPACK_PUBLICPATH=/


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

docker-compose.yml to enable hot-reloading

version: '3.8'
services:
  gatsby:
    build: .
    volumes:
      - .:/usr/src/app
      - /usr/src/app/node_modules
    ports:
      - "8001:8001"
    environment:
      NODE_ENV: development
      CHOKIDAR_USEPOLLING: "1"
      GATSBY_WEBPACK_PUBLICPATH: "/"
    command: npm run develop

Start the app:

docker-compose up --build