Skip to main content

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

  1. 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.
  2. Set Working Directory:

    WORKDIR /app
    • Defines /app as the working directory inside the container where commands will be executed and files will be located.
  3. Copy requirements.txt:

    COPY requirements.txt .
    • Copies the requirements.txt file from the host machine into the /app directory in the container.
  4. Install Dependencies:

    RUN pip install --no-cache-dir -r requirements.txt
    • Installs Python dependencies listed in requirements.txt using pip. The --no-cache-dir flag ensures that pip does not save cached files, reducing the size of the final image.
  5. Copy Application Files:

    COPY . .
    • Copies all the files from the current directory on the host machine to the /app directory in the container.
  6. 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 using docker run -p).
  7. Run Application:

    CMD ["uvicorn", "main:app", "--host", "0.0.0.0"  , "--port", "8001"]
    • Specifies the command to run when the container starts:
      • uvicorn is the ASGI server used to run the FastAPI app.
      • main:app tells uvicorn to find the app object in the main.py file.
      • --host 0.0.0.0 makes the application accessible from outside the container.
      • --port 8001 specifies the port the application will run on inside the container.

Purpose of This Dockerfile

This Dockerfile is tailored for a Python-based application (likely a FastAPI project). It:

  1. Uses Python 3.11 as the runtime environment.
  2. Sets up the application by installing dependencies and copying source code.
  3. Exposes the application on port 8001.
  4. Starts the application using uvicorn as 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 8001 on the host to port 8001 in the container, making the application accessible at http://localhost:8001.