In this lesson, you will learn how to transition your source code and external assets from your local machine into the isolated environment of a Docker image using the COPY and ADD instructions.
The Role of COPY
When you build an image, you need a way to bring your application code (like a Python script or an HTML file) into the image’s file system. COPY is the standard tool for this. It takes a file or directory from your local "build context" and places it into a destination inside your image.
For example, if you have an app.py file in your project folder, you add this to your Dockerfile:
COPY app.py /app/app.py
This instruction creates a new layer in your image, capturing the state of app.py. Because Docker uses a union file system, this file is now part of the immutable image, ready to be executed when the container starts.
The Role of ADD
ADD functions similarly to COPY, but it includes two "superpowers":
- Remote URLs: You can provide a URL, and Docker will download the file from the internet directly into your image during the build process.
- Auto-extraction: If the source file is a recognized archive format (like a
.tar.gz),ADDwill automatically unpack the contents into the destination directory.
Use ADD sparingly. Because it has these extra features, it can be less predictable than COPY. If you don't specifically need to download a remote file or extract an archive, stick to COPY to keep your builds explicit and easy to debug.
Best Practices
- Use COPY by default: It is clearer and helps prevent unexpected behavior from automatic extraction.
- Keep it local: Only use
ADDfor remote files when you are certain of the source integrity, as downloading files during a build can introduce variability into your image layers. - Order matters: Remember that these instructions create new image layers. Place them after your environment setup to ensure that changes to your source code don't force Docker to rebuild your entire system dependencies every time.
Key Takeaway: Use COPY to move local files into your image for predictable builds, and reserve ADD only when you specifically need to fetch remote URLs or automatically extract archives.