Dockerfile
What a Dockerfile Is
A Dockerfile is a script that contains instructions to build a Docker image. It defines the environment and dependencies required for an application to run in a container. Each instruction in the Dockerfile creates a layer in the Docker image, which contributes to the final container.
What This Dockerfile Does
-
Base Image:
FROM python:3.11-slim- This sets the base image to Python 3.11 with a slimmed-down version, which is lightweight and efficient for running Python applications.
-
Set Working Directory:
WORKDIR /app- Defines
/appas the working directory inside the container where commands will be executed and files will be located.
- Defines
-
Copy
requirements.txt:COPY requirements.txt .- Copies the
requirements.txtfile from the host machine into the/appdirectory in the container.
- Copies the
-
Install Dependencies:
RUN pip install --no-cache-dir -r requirements.txt- Installs Python dependencies listed in
requirements.txtusingpip. The--no-cache-dirflag ensures thatpipdoes not save cached files, reducing the size of the final image.
- Installs Python dependencies listed in
-
Copy Application Files:
COPY . .- Copies all the files from the current directory on the host machine to the
/appdirectory in the container.
- Copies all the files from the current directory on the host machine to the
-
Expose Port:
EXPOSE 8001- Declares that the container will listen on port
8001. This is primarily informational and doesn't actually publish the port (you still need to map it usingdocker run -p).
- Declares that the container will listen on port
-
Run Application:
CMD ["uvicorn", "main:app", "--host", "0.0.0.0" , "--port", "8001"]- Specifies the command to run when the container starts:
uvicornis the ASGI server used to run the FastAPI app.main:apptellsuvicornto find theappobject in themain.pyfile.--host 0.0.0.0makes the application accessible from outside the container.--port 8001specifies the port the application will run on inside the container.
- Specifies the command to run when the container starts:
Purpose of This Dockerfile
This Dockerfile is tailored for a Python-based application (likely a FastAPI project). It:
- Uses Python 3.11 as the runtime environment.
- Sets up the application by installing dependencies and copying source code.
- Exposes the application on port
8001. - Starts the application using
uvicornas the web server.
Example Usage
1. Build the Docker Image:
docker build -t my-python-app .
2. Run the Docker Container:
docker run -p 8001:8001 my-python-app
- Maps port
8001on the host to port8001in the container, making the application accessible athttp://localhost:8001.