Two Python projects may need different versions of the same package. A virtual environment keeps each project’s installed packages in its own directory, helping avoid version conflicts. It keeps projects organized, but it is not true isolation. section 2.1.1
For a local FastAPI project:
- From the project directory, create an environment named venv with python3 -m venv venv on macOS or Linux, or python -m venv venv on Windows. section 2.1.1
- Activate it with source venv/bin/activate on macOS or Linux, or .\venv\Scripts\activate on Windows. Activate it again whenever you return to the project. section 2.1.1
- Install dependencies with python -m pip install -r src/requirements.txt. The requirements file names packages such as fastapi, jinja2, uvicorn, and gunicorn. section 2.1.1
Do not commit the populated venv/ directory to Git: add venv/ to the project’s .gitignore. Keep requirements.txt instead so the packages can be installed again. This is similar to excluding a Node.js project’s node_modules/ directory while retaining package.json. section 2.3.2
Using an environment on a server
A manually deployed FastAPI app can create its environment at /opt/venv with python3 -m venv /opt/venv. Commands can then use /opt/venv/bin/python to install requirements and /opt/venv/bin/gunicorn to run the app; they do not need an activated shell. section 3.4.1
The same setup can be automated. An Ansible playbook installs Python support, creates /opt/venv if it does not exist, copies the application, and installs its requirements with /opt/venv/bin/pip. A Python Dockerfile likewise creates /opt/venv and installs requirements before starting a server with the environment’s Python. section 4.2.3 section 5.3.2
Listing 5.6 Python Dockerfile for browsing
# get our Python image
FROM python:3.11.4
# create and move to the /app directory
# all commands after will execute in this directory
WORKDIR /app
# copy our local src folder to /app in the container
COPY ./src/ /app
# Run os-level updates
RUN apt-get update && \
apt-get install -y python3-venv python3-dev python3-pip
# Create our Python virtual environment
RUN python3 -m venv /opt/venv
# Update the virtual environment pip
RUN /opt/venv/bin/python -m pip install --upgrade pip
# Install our project dependencies
# src/requirements.txt is our local version
RUN /opt/venv/bin/python -m pip install -r requirements.txt
# Run a server to expose copied files
CMD ["/opt/venv/bin/python", "-m", "http.server", "8080"]
See the environment’s creation, pip upgrade, dependency installation, and Python command together in a Dockerfile. section 5.3.2






