To create a Dockerfile that starts with a basic Ubuntu image, installs Python, and the necessary packages from a requirements.txt file, and finally runs main.py, you can follow the structure below. This Dockerfile assumes that you have a requirements.txt file in the same directory as your Dockerfile, which lists all the Python dependencies your application needs. It also assumes you have a main.py file that contains your FastAPI application.
Create a file called Dockerfile
, and put the following code inside:
# Use an official Ubuntu base image |
Here’s a step-by-step explanation of what each line in the Dockerfile does:
FROM ubuntu:latest
: Starts with the latest Ubuntu base image.WORKDIR /app
: Sets the working directory for any RUN, CMD, ENTRYPOINT, COPY, and ADD instructions that follow in the Dockerfile.RUN apt-get update
and the following line: Installs Python and pip by updating the package lists for the Ubuntu package manager and installing the Python3 and Python3-pip packages.COPY . /app
: Copies the current directory (where the Dockerfile resides) into the /app directory inside the container. This step assumes your requirements.txt and main.py are in the same directory as your Dockerfile.RUN pip3 install --no-cache-dir -r requirements.txt
: Installs the Python dependencies defined in requirements.txt without storing the cache, to keep the Docker image size smaller.EXPOSE 3000
: Informs Docker that the container listens on port 3000 at runtime. Note that exposing the port does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container.ENV UVICORN_HOST=0.0.0.0
andENV UVICORN_PORT=3000
: Sets environment variables to configure uvicorn to run on 0.0.0.0:3000. These are only necessary if your main.py utilizes these environment variables to configure the host and port; otherwise, they can be omitted.CMD ["python3", "main.py"]
: Specifies the command to run within the container, which starts your FastAPI application by running main.py with Python 3.
To build and run your Docker container, you would use the following commands in the directory containing your Dockerfile and application code:
# Build your Docker image |
# Run your Docker container |
This maps port 3000 of the container to port 3000 on your host, allowing you to access the FastAPI application by visiting http://localhost:3000 on your browser or using a tool like curl or Postman to send requests to your API.