0
0
DockerHow-ToBeginner · 4 min read

Docker Compose for React and Express: Setup Guide

Use a docker-compose.yml file to define two services: one for React and one for Express. Each service uses its own Dockerfile and shares a network, allowing them to run together easily with docker-compose up.
📐

Syntax

A docker-compose.yml file defines multiple services in a YAML format. Each service has a build context pointing to its Dockerfile, a ports section to expose ports, and optional volumes for live code updates. Services share a default network for communication.

yaml
version: '3.8'
services:
  react-app:
    build: ./react
    ports:
      - '3000:3000'
    volumes:
      - ./react:/app
    environment:
      - CHOKIDAR_USEPOLLING=true
  express-api:
    build: ./express
    ports:
      - '5000:5000'
    volumes:
      - ./express:/app
💻

Example

This example shows a docker-compose.yml file that runs a React frontend on port 3000 and an Express backend on port 5000. Each service uses its own Dockerfile and mounts local code for easy development.

yaml
version: '3.8'
services:
  react-app:
    build: ./react
    ports:
      - '3000:3000'
    volumes:
      - ./react:/app
    environment:
      - CHOKIDAR_USEPOLLING=true
  express-api:
    build: ./express
    ports:
      - '5000:5000'
    volumes:
      - ./express:/app
Output
Starting react-express-react-app_react-app_1 ... done Starting react-express-react-app_express-api_1 ... done react-app_1 | Compiled successfully. express-api_1 | Server running on port 5000
⚠️

Common Pitfalls

Common mistakes include not exposing ports correctly, missing volume mounts for live reload, or forgetting to set environment variables needed for React's file watching. Also, ensure backend and frontend use different ports to avoid conflicts.

yaml
version: '3.8'
services:
  react-app:
    build: ./react
    ports:
      - '3000:3000'
  express-api:
    build: ./express
    ports:
      - '3000:5000'  # Wrong: port conflict

# Corrected:
version: '3.8'
services:
  react-app:
    build: ./react
    ports:
      - '3000:3000'
  express-api:
    build: ./express
    ports:
      - '5000:5000'
📊

Quick Reference

  • version: Compose file format version.
  • services: Defines each container.
  • build: Path to Dockerfile directory.
  • ports: Maps container ports to host.
  • volumes: Syncs local code for live updates.
  • environment: Sets environment variables.

Key Takeaways

Use separate services in docker-compose for React and Express with distinct ports.
Mount volumes to enable live code changes during development.
Set environment variables like CHOKIDAR_USEPOLLING for React file watching inside Docker.
Avoid port conflicts by mapping different host ports for frontend and backend.
Run both services together easily with the single command: docker-compose up.