Course contentsShow
← Python
Lesson 521 of 1,0608. Professional Tooling and PackagingFree lesson

Automating Environment Cleanup with Manifests

You will create .gitignore and .dockerignore files to exclude build artifacts, cache files, and virtual environments from your version control system.

In this lesson, you will learn how to automate the protection of your version control system from "environment clutter" by using .gitignore and .dockerignore manifests.

When you develop Python projects, you inevitably generate thousands of files that don't belong in your source code repository: virtual environment binaries, byte-compiled cache files, and build artifacts. Committing these files not only bloats your repository size but can also cause "it works on my machine" bugs when others pull your code and inherit your specific path configurations.

The Power of Ignore Manifests

Instead of manually selecting which files to exclude, you use manifest files—.gitignore for Git and .dockerignore for container builds. These files act as a "do-not-track" list for your automation tools.

To keep your project clean, create a .gitignore file in your root directory and add the following standard patterns:

# Python environment and cache
venv/
.venv/
__pycache__/
*.pyc

# Distribution / Build artifacts
dist/
build/
*.egg-info/

# Local configuration
.env

Keeping Docker Lean

When you build a Docker image, you usually copy your local directory into the container. If you don't exclude your local venv/ or .pyc files, the build process will be slow and the resulting image size will balloon significantly.

By creating a .dockerignore file with the exact same patterns as your .gitignore, you ensure that the COPY . . command in your Dockerfile skips these heavy, machine-specific files entirely. This keeps your build process deterministic and efficient.

Best Practices

  1. Be Proactive: Initialize your .gitignore the moment you create a project. It is much harder to remove files from a Git history once they have already been committed.
  2. Global Settings: If you find yourself adding the same lines to every project, you can configure a global ~/.gitignore file that Git will respect across all your local repositories.
  3. Consistency: Treat your .dockerignore as a mirror of your .gitignore. If a file shouldn't be in your source code, it almost certainly shouldn't be in your container image.

Key Takeaway: Use .gitignore and .dockerignore manifests to automatically filter out transient artifacts and environments, ensuring your repository remains lightweight, portable, and free of machine-specific noise.