Where to Use COPY and ADD in Your Dockerfile

Where to Use COPY and ADD in Your Dockerfile

When creating Docker images, COPY and ADD help you manage files inside your container. Here's a quick guide on how to use them with a basic Apache web server example.

What Are COPY and ADD?

COPY: Moves files from your computer into the Docker image. Use this for straightforward file transfers.

ADD: Similar to COPY, but can also handle compressed files and download files from URLs.

When to Use COPY

Copy Files: Use COPY to move files like your website content into the Docker image.

# Use the official Apache image
FROM httpd:2.4

# Copy website files
COPY html/ /usr/local/apache2/htdocs/

# Expose port 80
EXPOSE 80

When to Use ADD

Extract Tarballs: Use ADD to extract compressed files (e.g., .tar.gz) directly into the Docker image.

# Use the official Apache image
FROM httpd:2.4

# Download a file from a URL
ADD https://example.com/file.txt /usr/local/apache2/htdocs/

# Expose port 80
EXPOSE 80

Best Practices

Use COPY for Simple Tasks: It’s easier and more straightforward.
Use ADD for Tarballs or Downloads: If you need to handle compressed files or download from a URL.

Conclusion

Use COPY for basic file transfers and ADD for more advanced needs like extracting tarballs or downloading files. This helps keep your Dockerfiles clear and efficient.