Mastodon hachyterm.io

Adding a Postgres database to an existing service is fairly straightforward with docker-compose.

Create a Dockerfile for your main service. For example, here’s a simple Docker container with Node:

FROM node:12.14.0-alpine3.9

ENV NPM_CONFIG_PREFIX=/home/node/.npm-global
RUN npm install npm@latest -g --silent

WORKDIR /opt/app

COPY package*.json /opt/app/
RUN npm install --no-optional && npm cache clean --force

ENV PATH /opt/app/node_modules/.bin:$PATH
ENV PATH=$PATH:/home/node/.npm-global/bin
ARG NODE_ENV=production
ENV NODE_ENV $NODE_ENV
ARG PORT=3000
ENV PORT $PORT
EXPOSE $PORT 8229 8230

COPY . .

CMD ["npm", "run", "watch"]

The Dockerfile starts from the official Node container, updates npm globally, installs the necessary packages, and runs an npm command (as root user in development mode).

Here’s a docker-compose.yml file for the service:

version: '3.7'

  users-service:
    build:
      context: ./users-service
      dockerfile: Dockerfile
      args:
        - NODE_ENV=development
    environment:
      - NODE_ENV=development
    volumes:
      - ./users-service:/opt/app
      - /opt/app/node_modules
    ports:
      - 8080:3000
      - 8229:9229
      - 8230:9230

Now, add a database:

users-service-db:
  image: postgres:12-alpine
  ports:
    - 5436:5432
  environment:
    - POSTGRES_DB=db
    - POSTGRES_USER=postgres
    - POSTGRES_PASSWORD=postgres

As you can see, you only have to add a few lines of code.

You can set up the Postgres variables as environment variables of the main service. Plus, the users-service depends on the database:

version: '3.7'

  users-service:
    build:
      context: ./users-service
      dockerfile: Dockerfile
      args:
        - NODE_ENV=development
    environment:
      - NODE_ENV=development
      - DATABASE_URL=postgres://postgres:postgres@users-service-db:5432/db?charset=UTF8
    volumes:
      - ./users-service:/opt/app
      - /opt/app/node_modules
    ports:
      - 8080:3000
      - 8229:9229
      - 8230:9230
    depends_on:
      - users-service-db

  users-service-db:
    image: postgres:12-alpine
    ports:
      - 5436:5432
    environment:
      - POSTGRES_DB=db
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres

Run docker-compose build to build the containers. Note that you don’t have to write a Dockerfile for the Postgres service.

Run the containers with docker-compose up (or docker-compose up -d).

Enter the Postgres container with psql:

docker-compose exec users-service-db psql -U postgres

Here’s a cheatsheet for the psql commands: PostgreSQL Cheat Sheet.