Suresh Kumar
sureshdsk.dev

sureshdsk.dev

Docker - Difference between COPY and ADD in Dockerfile

Docker - Difference between COPY and ADD in Dockerfile

Learn the COPY and ADD instruction in Dockerfile and use cases for both COPY and ADD instructions.

Suresh Kumar's photo
Suresh Kumar

Published on Jul 10, 2021

2 min read

Subscribe to my newsletter and never miss my upcoming articles

COPY and ADD are both Dockerfile instructions that does similar operation. Both instructions are used to copy files into a Docker image. Let's look at some use cases for both.

COPY instruction in a Dockerfile

  • The COPY instruction copies files or directories into the Docker image.
  • It takes a src and destination as arguments.
  • Source can be absolute or relative from current WORKDIR or wild cards.
  • Destination path can be absolute or relative to current WORKDIR.

Examples:

COPY ./requirements.txt /app/requirements.txt 
COPY package.json package-lock.json /app
COPY package*.json /app
COPY . /app

Using COPY instruction to add source code into Docker Image

FROM python:3.8.0

# set working directory
WORKDIR /app

# add requirements
COPY ./requirements.txt /app/requirements.txt

# install requirements
RUN pip install -r requirements.txt

# copy source code to /app
COPY . /app

# run server
CMD python main.py

# expose 
EXPOSE 5000

ADD instruction in a Dockerfile

  • The ADD instruction copies files, directories, remote file or tar archive into the Docker image.
  • It takes a src and destination as arguments.
  • Source can be files and directories.
  • Source can be a URL. The ADD instruction will download the file from the URL and save it to the destination. We don't need to use curl or wget to download a file.
  • Source can be a local tar/zip archive. The ADD instruction will automatically extract it to the destion. We don't need to run unarchive commands manually.
  • Use ADD when you want download a file from a URL or extract local archive file.

ADD ./example.tar.gz /tmp/

ADD https://bootstrap.pypa.io/get-pip.py /get-pip.py

Using ADD instruction to update pip package manager

FROM python:3.8.0

# set working directory
WORKDIR /app

# add requirements
COPY ./requirements.txt /app/requirements.txt

# updating pip
ADD https://bootstrap.pypa.io/get-pip.py /get-pip.py
RUN python /get-pip.py

# install requirements
RUN pip install -r requirements.txt

# add source code
COPY . /app

# run server
CMD python main.py

# expose 
EXPOSE 5000

If you find this article helpful, please do like and comment on this article. If you have any suggestions or feedbacks, feel free to comment.

Stay tuned for upcoming articles. Subscribe to the newsletter and Connect with me on twitter to get my future articles.

Did you find this article valuable?

Support Suresh Kumar by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this