🎄Use Docker - even locally🌟

Dec 24 2023

Back to 2023 Advent Calendar

Why use Docker locally?

  1. Consistency Across Environments: Docker containers encapsulate your application along with its environment, ensuring that it works uniformly across different development and production setups.
  2. Isolation: Containers operate independently, so your Next.js app and PostgreSQL won’t interfere with other projects or system-wide settings.
  3. Portability: Docker containers can be easily shared and run on any system with Docker installed, regardless of the underlying OS.
  4. Scalability and Efficiency: Docker allows easy scaling of your application and makes optimal use of system resources.

Example

Let's say you have a NextJS app that uses PostgreSQL. You want to develop locally, but you don't want to install PostgreSQL on your machine.

You also want to make sure that your app works the same way in production as it does locally.

You can use Docker to create a container for your NextJS app and a container for PostgreSQL.

You can then link the two containers together so that they can communicate with each other.

  1. Assuming you already have your NextJS project setup, if not - check how to install

  2. install docker (on mac) https://docs.docker.com/desktop/install/mac-install/

  3. create a docker-compose.yml file (in the same directory as your NextJS project)

version: '3'
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "3000:3000"
    environment:
      - DATABASE_URL=postgres://user:password@db:5432/dbname
    depends_on:
      - db
    volumes:
      - .:/usr/src/app
      - /usr/src/app/node_modules

  db:
    image: postgres
    environment:
      POSTGRES_DB: dbname
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:
  1. create a Dockerfile
# Use an official Node.js runtime as a parent image
FROM node:latest

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

# Copy the current directory contents into the container at /usr/src/app
COPY . .

# Install any needed packages specified in package.json
RUN npm install

# Make port 3000 available to the world outside this container
EXPOSE 3000

# Run the app when the container launches
CMD ["npm", "run", "dev"]
  1. run docker-compose up

  2. open http://localhost:3000

  3. when you are done, cmd+c to stop the containers.