Containers

Copy files to and from a container

  1. Copy an nginx.conf file from the host current directory to /etc/nginx directory in nginx-container:
docker cp nginx.conf nginx-container:/etc/nginx/nginx.conf

/etc/nginx/nginx.conf file in nginx-container will be owned by the container root user, root group. If /etc/nginx/nginx.conf file exists in nginx-container, it will be overwritten.

  1. Copy an nginx.conf file, owned by test user, test group from the host current directory to /etc/nginx directory in nginx-container, setting its ownership to test user, test group:
docker cp -a nginx.conf nginx-container:/etc/nginx/nginx.conf
  1. There is a symbolic link nginx.conf-link in the current directory, which points to the nginx.conf file. Copy the nginx.conf-link symbolic link to /etc/nginx directory in nginx-container:
docker cp nginx.conf-link nginx-container:/etc/nginx/nginx.conf-link

The nginx.conf-link symbolic link is copied.

  1. Following the example 3, copy the nginx.conf file via the nginx.conf-link symbolic link:
docker cp -L nginx.conf-link nginx-container:/etc/nginx/nginx.conf

With -L option indicated, docker cp copies the nginx.conf pointed to by the nginx.conf-link symbolic link.

  1. Copy html directory to /usr/share/nginx directory in nginx-container. An elegant solution using tar:
tar -cf - html | docker exec -i nginx-container tar -C /usr/share/nginx -xf -

Explanation:

  • tar -cf -, so - is used as the archive name, means that the created archive is written to standard output,
  • tar -xf - means that the archive is read from the standard input,
  • tar -C /usr/share/nginx means that the archive is extracted to the /usr/share/nginx directory.

Return to the host terminal without exiting container

If you have created a container by executing a docker run command, for example:

docker run -it nginx:alpine ash

After you type exit, the container main process terminates and the container status changes to Exited(0).

If you want to leave the container running, but return to the host machine terminal, type Ctrl+pq.

Execute docker ps and you will see that the container is still running.

Run a script in container and redirect output to a file on the host machine

Execute scriptInContainer.sh and redirect output to the script.out file:

docker exec testContainer bash -c ". /tmp/scriptInContainer.sh" > script.out

More details on this example: Run a script in container and redirect output to a file on the host machine