3.1 Creating a Dockerfile for the Frontend (ReactJS)
At this stage, we're gonna create a Dockerfile for each of the three services in our multi-container app: the frontend built with ReactJS, the backend using Python (Flask), and the PostgreSQL database. A Dockerfile contains instructions for building a Docker image for each service.
Create a Dockerfile in the frontend directory:
cd frontend
touch Dockerfile
Dockerfile content for the frontend:
# Use the base image for node
FROM node:14
# Set the working directory
WORKDIR /app
# Copy package.json and package-lock.json to install dependencies
COPY package*.json ./
# Install dependencies
RUN npm install
# Copy the rest of the project files
COPY . .
# Set port 3000
EXPOSE 3000
# Start the app
CMD ["npm", "start"]
This Dockerfile performs the following steps:
- Uses the base image
node:14
. - Sets the working directory to
/app
. - Copies the
package.json
andpackage-lock.json
files. - Installs dependencies using
npm install
. - Copies all project files into the working directory.
- Exposes port
3000
for app access. - Starts the app using
npm start
.
3.2 Creating a Dockerfile for the Backend (Flask)
Create a Dockerfile in the backend directory:
cd backend
touch Dockerfile
Dockerfile content for the backend:
# Using python base image
FROM python:3.12
# Setting up the working directory
WORKDIR /app
# Copying requirements.txt to install dependencies
COPY requirements.txt ./
# Installing dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Copying the rest of the project files
COPY . .
# Specifying port 5000
EXPOSE 5000
# Running the application
CMD ["python", "run.py"]
This Dockerfile performs the following steps:
- Uses the
python:3.12
base image. - Sets the working directory to
/app
. - Copies the
requirements.txt
file. - Installs dependencies using
pip install
. - Copies all project files to the working directory.
- Exposes port
5000
for accessing the app. - Runs the app using
python run.py
.
3.3 Creating a Dockerfile for the Database (PostgreSQL)
For the PostgreSQL database, we’re gonna use the official image, so creating our own Dockerfile is not required. Instead, we’ll configure PostgreSQL through docker-compose.yml
.
3.4 Building and Testing Docker Images
After creating the Dockerfile for the frontend and backend, it's important to test their build.
Building the Docker image for the frontend:
cd frontend
docker build -t task_management_frontend .
Building the Docker image for the backend:
cd ../backend
docker build -t task_management_backend .
Checking the containers:
Running the container for the frontend:
docker run -p 3000:3000 task_management_frontend
Running the container for the backend:
docker run -p 5000:5000 task_management_backend
Go to http://localhost:3000 to check the frontend, and http://localhost:5000 to check the backend.
GO TO FULL VERSION