Track 2: Volumes and Docker Compose
Step-by-Step Guide
Open Terminal:
Launch PowerShell if not default
Create a New Project Directory:
Navigate to the location where you want to create your project directory.
Create a new directory for your project:
mkdir fastapi-docker
cd fastapi-docker
code .This will open a new VScode window
Open the terminal in VSCode (Ctrl + `).
Create the
srcDirectory:Inside your project directory, create a
srcdirectory:
mkdir srcCreate
main.pyInsidesrc:Navigate into the
srcdirectory and create themain.pyfile:
Add Code to
main.py:Open
main.pyin VSCode and add the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, World!"}
# To run the server, use the command: uvicorn filename:app --reload
Create
requirements.txt:Go back to the root of your project directory and create a
requirements.txtfile:
cd ..
touch requirements.txtAdd the following dependencies to
requirements.txt:
fastapi
uvicornCreate the
Dockerfile:In the root of your project directory, create a
Dockerfile: DockerfileAdd the following content to the
Dockerfile:
# Use the official Python image from the Docker Hub
FROM python:3.13-slim
# Set the working directory in the container
WORKDIR /code
# Copy the requirements file into the container
COPY ./requirements.txt ./
# Install the dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Copy the application code into the /src directory
COPY ./src ./src
# Command to run the application with auto-reload
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]Build and Run the Docker Container:
Build the Docker image:
docker build -t fastapi .Analyzing the use of Volume
Run the Docker container without the volume mounting
docker run -d -p 8000:8000 fastapiRun the Docker container with volume mounting:
docker run -d -p 8000:8000 -v ${PWD}:/code fastapiAccess the Application
Open your web browser and go to http://localhost:8000. Any changes you make to main.py in the src directory will be automatically reflected in the running container.
Automate Docker creation using YML
Create docker-compose.yml file in parent directory
services:
app:
build: .
container_name: python-cont
command: uvicorn src.main:app --host 0.0.0.0 --port 8000 --reload
ports:
- "8000:8000"
volumes:
- .:/codeRun docker compose
docker compose up --build -dLast updated