A .dockerignore file tells Docker which files and directories to leave out of the build context and container image. Place it beside the Dockerfile to prevent broad COPY or ADD operations from including unwanted files. section 5.3.2 section 5.3.3
Use patterns that make exclusions explicit:
- Use absolute paths for individual files. section 5.3.3
- Use relative folder paths prefixed with **/ to match folders anywhere. section 5.3.3
- End folder patterns with / so Docker ignores everything in the stated folder. section 5.3.3
- Keep the file even when Git and .gitignore already exclude most unwanted files; a smaller image can reduce build and deploy time and limit accidental exposure of environment or secret files. section 5.3.3
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"]
Browse the Python Dockerfile whose broad COPY operation motivates filtering the build context. section 5.3.2
Listing 5.8 Python .dockerignore sample
# ignore Python cached files **/__pycache__/ *.py[cod] # ignore env files *.env
Browse a practical Python pattern set that excludes cached bytecode and environment files. section 5.3.3
Listing 5.12 Node.js Dockerignore
# ignore node modules **/node_modules/ # ignore env files *.env
Browse the Node.js variant, which excludes node_modules and environment files. section 5.4.1



