I am trying to build a backup and restore solution for the Docker containers that we work with.
I have Docker base image that I have created, ubuntu:base, and do not want have to rebuild it each time with a Docker file to add files to it.
I want to create a script that runs from the host machine and creates a new container using the ubuntu:base Docker image and then copies files into that container.
How can I copy files from the host to the container?
Answwers
You can copy files from the host to a Docker container using the docker cp
command. Here's how you can do it:
- First, start the container based on the
ubuntu:base
image.
docker run -d --name mycontainer ubuntu:base
Replace mycontainer
with the name you want to give to your container.
- Use the
docker cp
command to copy files from the host machine to the container.
docker cp /path/to/local/file mycontainer:/path/in/container
Replace /path/to/local/file
with the path to the file on your host machine that you want to copy, and replace /path/in/container
with the path inside the container where you want to copy the file.
For example, if you want to copy a file named backup.tar
from your host's /backup
directory to the /data
directory inside the container named mycontainer
, you would run:
docker cp /backup/backup.tar mycontainer:/data/backup.tar
The file backup.tar
will now be available inside the container at /data/backup.tar
.
- You can also use
docker cp
to copy entire directories:
docker cp /path/to/local/directory mycontainer:/path/in/container
Replace /path/to/local/directory
with the path to the directory on your host machine that you want to copy, and replace /path/in/container
with the path inside the container where you want to copy the directory.
docker cp /backup/data mycontainer:/data
This will copy the data
directory from your host to the /data
directory inside the container.
Once you've copied the necessary files into the container, you can stop and restart the container as needed. Remember that any changes made inside the container will not persist unless you commit them to a new image or use Docker volumes to persist data.