dockerfile which uses python 3.12, in main folder is main.py with files in api folder where there are models.py and database.py, runs uvicorn port 8000
Assistant
To create a Dockerfile that builds an image with Python 3.12, runs a Python application stored in main.py at the root of your project directory, and has additional files in the api folder (like models.py and database.py), you'll want to follow a few steps. We will also set up the container to run a Uvicorn server, which is an ASGI server, on port 8000 for your FastAPI application.
Here's an example Dockerfile that accomplishes this:
Dockerfile
# Use the official Python image that includes Python 3.12
FROM python:3.12-slim
# Set the working directory inside the container
WORKDIR /app
# Copy the requirements file into the container
COPY requirements.txt .
# Install any dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Copy the rest of your app's source code from your host to your image filesystem.
COPY . .
# Command to run the Uvicorn server:
# - app.main: the file (main.py) and variable or application (app) containing your FastAPI application.
# - --host 0.0.0.0: ensures the web service is accessible on any IP assigned to your container.
# - --port 8000: specifies the port the Uvicorn server will listen on.
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Considerations for this Dockerfile:
Replace requirements.txt with your actual requirements file that should include fastapi and uvicorn, and any other dependencies your application requires.
Ensure main.py contains your FastAPI app instance and that it is named app i.e, app = FastAPI().
Make sure to expose the correct port in your Dockerfile if you want to explicitly document that your service listens on a specific port. This is done with the EXPOSE instruction (e.g., EXPOSE 8000). However, this is more for documentation purposes; to actually map the port so it's accessible outside the container, you'll need to specify the port mapping when you run the container using the -p option with docker run.
For more complex projects, consider using a .dockerignore file to exclude files and directories (like virtual environments or IDE configurations) that don't need to be copied into your Docker image.
If your main.py lies in another folder or is named differently, adjust the CMD in the Dockerfile to match your setup, for example, if main.py is inside the api folder and the FastAPI app is still named app, you would update the command to: