express react docker container example

  1. Install Node.js and npm:
curl -fsSL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
  1. Create a new Express.js app:
mkdir express-react-app
cd express-react-app
npm init -y
  1. Install Express.js and create a basic server:
npm install express

Create a file named server.js:

const express = require('express');
const app = express();
const port = 3001;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
  1. Install React.js and create a basic React app:
npx create-react-app client
  1. Create a Dockerfile for the Express.js app:

Create a file named Dockerfile:

# Use the official Node.js image as a base image
FROM node:14

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

# Copy package.json and package-lock.json to the working directory
COPY package*.json ./

# Install app dependencies
RUN npm install

# Copy the rest of the application code to the working directory
COPY . .

# Expose the port the app runs on
EXPOSE 3001

# Command to run the application
CMD ["node", "server.js"]
  1. Create a Dockerfile for the React app:

In the client directory, create a file named Dockerfile:

# Use the official Node.js image as a base image
FROM node:14

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

# Copy package.json and package-lock.json to the working directory
COPY package*.json ./

# Install app dependencies
RUN npm install

# Copy the rest of the application code to the working directory
COPY . .

# Build the React app
RUN npm run build

# Expose the port the app runs on
EXPOSE 3000

# Command to run the application
CMD ["npm", "start"]
  1. Create a Docker Compose file to manage both containers:

Create a file named docker-compose.yml:

version: '3'

services:
  express-app:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "3001:3001"
    depends_on:
      - react-app

  react-app:
    build:
      context: ./client
      dockerfile: Dockerfile
    ports:
      - "3000:3000"
  1. Build and run the Docker containers:
docker-compose up --build

The Express app will be accessible at http://localhost:3001 and the React app at http://localhost:3000.