How to edit a file dynamically in a running docker container - docker

Background
I had build a npm server(sinopia) docker image(https://github.com/feuyeux/docker-atue/blob/master/docker-images/feuyeux_sinopia.md), and in the CMD line, it will run the start.sh every time when the container is generated.
CMD ["/opt/sinopia/start.sh"]
This shell will create a yaml file dynamically.
sed -e 's/\#listen\: localhost/listen\: 0.0.0.0/' -e 's/allow_publish\: admin/allow_publish\: all/' /tmp/config.yaml > /opt/sinopia/config.yaml
Question
I wish I could edit this config.yaml when the container is running, because I hope the content should be changed on demand.
see the snapshot photo
As shown above, the first line runs a sinopia container, and in this container, there's /opt/sinopia/config.yaml. But I don't know how to obtain this running container and edit and check this file.
If I did as the line of sinopia-ls, there's a new container runs instead of the before running one.
Thanks guys!
Answer(details please see below what I accepted)
sudo nsenter --target $PID --mount --uts --ipc --net --pid
root#58075317e47d:/# ls /opt/sinopia/
config.yaml config_gen.js start.sh storage
root#58075317e47d:/# cat /opt/sinopia/config.yaml

With docker 1.3, there is a new command docker exec. This allows you to enter a running docker:
docker exec -it <container-id> bash

You named your container, so you can find it using that name.
Then use nsenter (man nsenter) to send the command you want to do.
nsenter --target $$(docker inspect --format {{.State.Pid}} <container_name_or_ID>) --mount --uts --ipc --net --pid <cmd>
More info and solution on how to write inside of a running container : If you run SSHD in your Docker containers, you're doing it wrong!

you just need to mount the folder using -v as an option. i give an example
let's say i have /home/awan/config.yml <--- this file is always dynamic must not put it inside container
i run my container so i can mount that folder into my container
#sudo docker run -i -t -v /home/awan:/home/ubuntu/awan ubuntu/14.04 /bin/bash
after that you just edit config.yml in your /home/awan/config.yml every changes that you applied automaticaly applied inside your docker container (/home/ubuntu/awan/config.yml) because you mount it

Related

Where is the file I mounted at run time to Docker?

I mounted my secret file secret.json at runtime to a local docker, and while it works, I don't seems to find this volume anywhere.
My docker file looks like this and has no reference to secret:
RUN mkdir ./app
ADD src/python ./app/src/python
ENTRYPOINT ["python"]
Then I ran
docker build -t {MY_IMAGE_NAME} .
docker run -t -v $PATH_TO_SECRET_FILE/:/secrets/secret.json \
-e MY_CREDENTIALS=/secrets/secret.json \
{MY_IMAGE_NAME} ./app/src/python/runner.py
This runs successfully locally but when I do
docker run --entrypoint "ls" {MY_IMAGE_NAME}
I don't see the volume secrets.
Also, if I run
docker volume ls
it doesn't have anything that looks like secrets.
Without environment variable MY_CREDENTIALS the script won't run. So I am sure the secret file is mounted somewhere, but can't figure out where it is. Any idea?
You are actually creating two separate containers with the commands you are running. The first docker run command creates a container from the image you have built with the volume mounted and then the second command creates a new container from the same image but without any volumes (as you don't define any in your command)
I'd suggest you give your container a name like so
docker run -t -v $PATH_TO_SECRET_FILE/:/secrets/secret.json \
-e MY_CREDENTIALS=/secrets/secret.json \
--name my_container {MY_IMAGE_NAME} ./app/src/python/runner.py
and then run exec on that container
docker exec -it my_container sh

How to re-mount a docker volume without overriding existing files?

When running Docker, you can mount files and directories using the --volume option. E.g.:
docker run --volume /remote ./local myimage
I'm running a docker image that defines VOLUMESs in the Dockerfile. I need to access a config file that happens to be inside one of the defined volumes. I'd like to have that file "synced" on the host so that I can edit it. I know I could run docker exec ..., but I hope to circumvent that overhead for only editing one file. I found out that the volumes created by the VOLUMES line are stored in /var/lib/docker/volumes/<HASH>/_data.
Using docker inspect I was able to find the directory that is mounted:
docker inspect gitlab-runner | grep -B 1 '"Destination": "/etc/gitlab-runner"' | head -n 1 | cut -d '"' -f 4
Output:
/var/lib/docker/volumes/9c233c085c36380c6c33035222c16e5d061368c5060cc81dda2a9a713a2b2b3b/_data
So the question is:
Is there a way to re-mount volumes defined in an image? OR to somehow get the directory easier than my oneliner above?
EDIT after comments by zeppelin I've tried rebinding the volume with no success:
$ mkdir etc
$ docker run -d --name test1 gitlab/gitlab-runner
$ docker run -d --name test2 -v ~/etc:/etc/gitlab-runner gitlab/gitlab-runner
$ docker exec test1 ls /etc/gitlab-runner/
certs
config.toml
$ docker exec test2 ls /etc/gitlab-runner/
# empty. no files
$ ls etc
# also empty
docker inspect shows correctly that the volume is bound to ~/etc, but the files inside the container at /etc/gitlab-runner/ seem lost.
$ docker run -d --name test1 gitlab/gitlab-runner
$ docker run -d --name test2 -v ~/etc:/etc/gitlab-runner gitlab/gitlab-runner
You've got two different volume types there. One I call an anonymous volume (a very long uuid visible when you run docker volume ls). The second is a host volume or bind mount that maps a directory on the host directly into the container. So each container you spun up is looking at different places.
Anonymous volumes and named volumes (docker run -d -v mydata:/etc/gitlab-runner gitlab/gitlab-runner) get initialized to the contents of the image at that directory location. This initialization only happens when the volume is empty and is mounted into a new container. Host volumes, as you've seen, only get the contents of the host filesystem, even if it's empty at that location.
With that background, the short answer to your question is no, you cannot mount a file inside the container back out to your host. But you can copy the file out with several methods, assuming you don't overlay the source of the file with a host volume mount. With a running container, there's the docker cp command. Personally, I like:
docker run --rm -v ~/etc:/target gitlab/gitlab-runner \
cp -av /etc/gitlab-runner/. /target/.
If you have a named volume with data you want to copy in or out, you can use any image with the tools you need to do the copy:
docker run --rm -v mydata:/source -v ~/etc:/target busybox \
cp -av /source/. /target/.
Try to avoid modifying data inside a container from the host directly, much nicer is when you wrap your task into another container that you then start with "--volumes-from" option when possible in your case.
Not sure I understood your problem, anyway, as for the documentation you mention,
The VOLUME instruction creates a mount point with the specified name
and marks it as holding externally mounted volumes from native host or
other containers. [...] The docker run command initializes the newly
created volume with any data that exists at the specified location
within the base image.
So, following the example Dockerfile , after having built the image
docker build -t mytest .
and having the container running
docker run -d -ti --name mytestcontainer mytest /bin/bash
you can access it from the container itself, e.g.
docker exec -ti mytestcontainer ls -l /myvol/greeting
docker exec -ti mytestcontainer cat /myvol/greeting
Hope it helps.

(dockerfile) for flag -v: bad mode specified

I have problems with the introduction of these instructions https://github.com/notabenoid/notabenoid-dockerfile
Out my error command
docker run -v `pwd`:/srv/example.com -p 127.0.0.1:8080:80 --name notabenoid notabenoid
I managed to turn the site, but my goal is to change a few files and pictures
How to edit files to container ?
use docker execto modify some files in a container, see the doc
https://docs.docker.com/engine/reference/commandline/exec/
check also the docs for docker run
https://docs.docker.com/engine/reference/commandline/run/
and the examples with -v
If You only need to change some files use docker cp.
docker run -p 127.0.0.1:8080:80 --name notabenoid notabenoid
docker cp notabenoid:/srv/example.com/file_to_change .
edit file
docker cp file_to_change notabenoid:/srv/example.com/file_to_change
where /srv/example.com/file_to_change is a path to file in container.
edit
Let's Your new logo is /home/Hellioob/new_logo.gif.
docker cp /home/Hellioob/new_logo.gif notabenoid:/notabenoid/site/www/i/logo.gif

Docker logging to container

I'm fresh user of Docker. The fist problem with which I'm faced is logging into container.
I'm found solutions to execute container bash commands by
docker exec -it ID bash
But, this is solution only for install/ remove packages. What to use if I want to edit nginx config in docker container ?
One of solutions can be loggin to container via ssh connection, but maybe Docker have something own for this ?, I mean easilly access without install OpenSSH ?
as you said,
docker exec -it container_id bash
and then use your favorite editor to edit any nginx config file. vi or nano is usually installed, but you may need to install emacs or vim, if this is your favorite editor
if you have just a few characters to modify,
docker exec container_id sed ...
might do the job. If you want to SSH into your container, you will need to install SSH and deal with the SSH keys, I am not sure this is what you need.
You're going about it the wrong way. You should rarely need to log into a container to edit files.
Instead, mount the nginx.conf with -v from the host. That way you can edit the file with your normal editor. Once you've got the config working the way you want it, you can then build a new image with it baked in.
In general, you have to get into the mindset of containers being ephemeral. You don't patch them; you throw them away and replace them with a fixed version.
How: Docker logging to container
Yes, you can. You can login the running container.
Exist docker exec or docker attach is not good enough. Looking to start a shell inside a Docker container? The solution is: jpetazzo/nsenter with two commands: nsenter and docker-enter.
If you are in Linux environment, then run below command:
docker run --rm -v /usr/local/bin:/target jpetazzo/nsenter
docker ps
# replace <container_name_or_ID> with real container name or ID.
PID=$(docker inspect --format {{.State.Pid}} <container_name_or_ID>)
nsenter --target $PID --mount --uts --ipc --net --pid
Then you are in that running container, you can run any linux commands now.
I prefer the other command docker-enter. Without login the container, you can directly run linux commands in container with docker-enter command. Second, I can't memory multiple options of nsenter command and no need to find out the container's PID.
docker-enter 0e8c248982c5 ls /opt
If you are mac or windows user, run docket with toolbox:
docker-machine ssh default
docker run --rm -v /usr/local/bin:/target jpetazzo/nsenter
PID=$(docker inspect --format {{.State.Pid}} 0e8c248982c5)
sudo nsenter --target $PID --mount --uts --ipc --net --pid
If you are mac or windows user, run docket with boot2docker:
boot2docker ssh
docker run --rm -v /usr/local/bin:/target jpetazzo/nsenter
PID=$(docker inspect --format {{.State.Pid}} 0e8c248982c5)
sudo nsenter --target $PID --mount --uts --ipc --net --pid
Note: The command docker run --rm -v /usr/local/bin:/target jpetazzo/nsenter only need run one time.
How: edit nginx config
For your second question, you can think about ONBUILD in Docker.
ONBUILD COPY nginx.conf /etc/nginx/nginx.conf
With this solution, you can:
edit nginx.conf in local, you can use any exist editor .
needn't build your image every time after you change nginx configuration.
every time, after you change nginx.conf file in local, you need stop, remove and re-run the containe, new nginx.conf file will be deployed into contrainer when docker run command.
You can refer the detail on how to use ONBUILD here: docker build

How to copy files from host to Docker container?

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?
The cp command can be used to copy files.
One specific file can be copied TO the container like:
docker cp foo.txt container_id:/foo.txt
One specific file can be copied FROM the container like:
docker cp container_id:/foo.txt foo.txt
For emphasis, container_id is a container ID, not an image ID. (Use docker ps to view listing which includes container_ids.)
Multiple files contained by the folder src can be copied into the target folder using:
docker cp src/. container_id:/target
docker cp container_id:/src/. target
Reference: Docker CLI docs for cp
In Docker versions prior to 1.8 it was only possible to copy files from a container to the host. Not from the host to a container.
Get container name or short container id:
$ docker ps
Get full container id:
$ docker inspect -f '{{.Id}}' SHORT_CONTAINER_ID-or-CONTAINER_NAME
Copy file:
$ sudo cp path-file-host /var/lib/docker/aufs/mnt/FULL_CONTAINER_ID/PATH-NEW-FILE
EXAMPLE:
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d8e703d7e303 solidleon/ssh:latest /usr/sbin/sshd -D cranky_pare
$ docker inspect -f '{{.Id}}' cranky_pare
or
$ docker inspect -f '{{.Id}}' d8e703d7e303
d8e703d7e3039a6df6d01bd7fb58d1882e592a85059eb16c4b83cf91847f88e5
$ sudo cp file.txt /var/lib/docker/aufs/mnt/**d8e703d7e3039a6df6d01bd7fb58d1882e592a85059eb16c4b83cf91847f88e5**/root/file.txt
The cleanest way is to mount a host directory on the container when starting the container:
{host} docker run -v /path/to/hostdir:/mnt --name my_container my_image
{host} docker exec -it my_container bash
{container} cp /mnt/sourcefile /path/to/destfile
Typically there are three types:
From a container to the host
docker cp container_id:./bar/foo.txt .
Also docker cp command works both ways too.
From the host to a container
docker exec -i container_id sh -c 'cat > ./bar/foo.txt' < ./foo.txt
Second approach to copy from host to container:
docker cp foo.txt mycontainer:/foo.txt
From a container to a container mixes 1 and 2
docker cp container_id1:./bar/foo.txt .
docker exec -i container_id2 sh -c 'cat > ./bar/foo.txt' < ./foo.txt
The following is a fairly ugly way of doing it but it works.
docker run -i ubuntu /bin/bash -c 'cat > file' < file
If you need to do this on a running container you can use docker exec (added in 1.3).
First, find the container's name or ID:
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b9b7400ddd8f ubuntu:latest "/bin/bash" 2 seconds ago Up 2 seconds elated_hodgkin
In the example above we can either use b9b7400ddd8f or elated_hodgkin.
If you wanted to copy everything in /tmp/somefiles on the host to /var/www in the container:
$ cd /tmp/somefiles
$ tar -cv * | docker exec -i elated_hodgkin tar x -C /var/www
We can then exec /bin/bash in the container and verify it worked:
$ docker exec -it elated_hodgkin /bin/bash
root#b9b7400ddd8f:/# ls /var/www
file1 file2
Create a new dockerfile and use the existing image as your base.
FROM myName/myImage:latest
ADD myFile.py bin/myFile.py
Then build the container:
docker build .
The solution is given below,
From the Docker shell,
root#123abc:/root# <-- get the container ID
From the host
cp thefile.txt /var/lib/docker/devicemapper/mnt/123abc<bunch-o-hex>/rootfs/root
The file shall be directly copied to the location where the container sits on the filesystem.
Another solution for copying files into a running container is using tar:
tar -c foo.sh | docker exec -i theDockerContainer /bin/tar -C /tmp -x
Copies the file foo.sh into /tmp of the container.
Edit: Remove reduntant -f, thanks to Maartens comment.
To copy a file from host to running container
docker exec -i $CONTAINER /bin/bash -c "cat > $CONTAINER_PATH" < $HOST_PATH
Based on Erik's answer and Mikl's and z0r's comments.
This is a direct answer to the question 'Copying files from host to Docker container' raised in this question in the title.
Try docker cp. It is the easiest way to do that and works even on my Mac. Usage:
docker cp /root/some-file.txt some-docker-container:/root
This will copy the file some-file.txt in the directory /root on your host machine into the Docker container named some-docker-container into the directory /root. It is very close to the secure copy syntax. And as shown in the previous post, you can use it vice versa. I.e., you also copy files from the container to the host.
And before you downlink this post, please enter docker cp --help. Reading the documentation can be very helpful, sometimes...
If you don't like that way and you want data volumes in your already created and running container, then recreation is your only option today. See also How can I add a volume to an existing Docker container?.
I tried most of the (upvoted) solutions here but in docker 17.09 (in 2018) there is no longer /var/lib/docker/aufs folder.
This simple docker cp solved this task.
docker cp c:\path\to\local\file container_name:/path/to/target/dir/
How to get container_name?
docker ps
There is a NAMES section. Don't use aIMAGE.
With Docker 1.8, docker cp is able to copy files from host to container. See the Docker blog post Announcing Docker 1.8: Content Trust, Toolbox, and Updates to Registry and Orchestration.
To copy files/folders between a container and the local filesystem, type the command:
docker cp {SOURCE_FILE} {DESTINATION_CONTAINER_ID}:/{DESTINATION_PATH}
For example,
docker cp /home/foo container-id:/home/dir
To get the contianer id, type the given command:
docker ps
The above content is taken from docker.com.
Assuming the container is already running, type the given command:
# cat /path/to/host/file/ | docker exec -i -t <container_id> bash -c "/bin/cat > /path/to/container/file"
To share files using shared directory, run the container by typing the given command:
# docker run -v /path/to/host/dir:/path/to/container/dir ...
Note: Problems with permissions might arise as container's users are not the same as the host's users.
This is the command to copy data from Docker to Host:
docker cp container_id:file path/filename /hostpath
docker cp a13fb9c9e674:/tmp/dgController.log /tmp/
Below is the command to copy data from host to docker:
docker cp a.txt ccfbeb35116b:/home/
Container Up Syntax:
docker run -v /HOST/folder:/Container/floder
In docker File
COPY hom* /myFolder/ # adds all files starting with "hom"
COPY hom?.txt /myFolder/ # ? is replaced with any single character, e.g., "home.txt"
In a docker environment, all containers are found in the directory:
/var/lib/docker/aufs/required-docker-id/
To copy the source directory/file to any part of the container, type the given command:
sudo cp -r mydir/ /var/lib/docker/aufs/mnt/required-docker-id/mnt/
Docker cp command is a handy utility that allows to copy files and folders between a container and the host system.
If you want to copy files from your host system to the container, you should use docker cp command like this:
docker cp host_source_path container:destination_path
List your running containers first using docker ps command:
abhishek#linuxhandbook:~$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS
PORTS NAMES
8353c6f43fba 775349758637 "bash" 8 seconds ago Up 7
seconds ubu_container
You need to know either the container ID or the container name. In my case, the docker container name is ubu_container. and the container ID is 8353c6f43fba.
If you want to verify that the files have been copied successfully, you can enter your container in the following manner and then use regular Linux commands:
docker exec -it ubu_container bash
Copy files from host system to docker container
Copying with docker cp is similar to the copy command in Linux.
I am going to copy a file named a.py to the home/dir1 directory in the container.
docker cp a.py ubu_container:/home/dir1
If the file is successfully copied, you won’t see any output on the screen. If the destination path doesn’t exist, you would see an error:
abhishek#linuxhandbook:~$ sudo docker cp a.txt ubu_container:/home/dir2/subsub
Error: No such container:path: ubu_container:/home/dir2
If the destination file already exists, it will be overwritten without any warning.
You may also use container ID instead of the container name:
docker cp a.py 8353c6f43fba:/home/dir1
If the host is CentOS or Fedora, there is a proxy NOT in /var/lib/docker/aufs, but it is under /proc:
cp -r /home/user/mydata/* /proc/$(docker inspect --format "{{.State.Pid}}" <containerid>)/root
This cmd will copy all contents of data directory to / of container with id "containerid".
docker cp [OPTIONS] SRC_PATH CONTAINER:DEST_PATH
The destination path must be pre-exist
tar and docker cp are a good combo for copying everything in a directory.
Create a data volume container
docker create --name dvc --volume /path/on/container cirros
To preserve the directory hierarchy
tar -c -C /path/on/local/machine . | docker cp - dvc:/path/on/container
Check your work
docker run --rm --volumes-from dvc cirros ls -al /path/on/container
Many that find this question may actually have the problem of copying files into a Docker image while it is being created (I did).
In that case, you can use the COPY command in the Dockerfile that you use to create the image.
See the documentation.
In case it is not clear to someone like me what mycontainer in #h3nrik answer means, it is actually the container id. To copy a file WarpSquare.mp4 in /app/example_scenes/1440p60 from an exited docker container to current folder I used this.
docker cp `docker ps -q -l`:/app/example_scenes/1440p60/WarpSquare.mp4 .
where docker ps -q -l pulls up the container id of the last exited instance. In case it is not an exited container you can get it by docker container ls or docker ps
docker cp SRC_PATH CONTAINER_ID:DEST_PATH
For example, I want to copy my file xxxx/download/jenkins to tomcat
I start to get the id of the container Tomcat
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
63686740b488 tomcat "catalina.sh run" 12 seconds ago Up 11 seconds 0.0.0.0:8080->8080/tcp peaceful_babbage
docker cp xxxx/download/jenkins.war 63686740b488:usr/local/tomcat/webapps/
This is a onliner for copying a single file while running a tomcat container.
docker run -v /PATH_TO_WAR/sample.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat
This will copy the war file to webapps directory and get your app running in no time.
My favorite method:
CONTAINERS:
CONTAINER_ID=$(docker ps | grep <string> | awk '{ print $1 }' | xargs docker inspect -f '{{.Id}}')
file.txt
mv -f file.txt /var/lib/docker/devicemapper/mnt/$CONTAINER_ID/rootfs/root/file.txt
or
mv -f file.txt /var/lib/docker/aufs/mnt/$CONTAINER_ID/rootfs/root/file.txt
The best way for copying files to the container I found is mounting a directory on host using -v option of docker run command.
There are good answers, but too specific. I find out docker ps is good way to get container id you're interested in. Then do
mount | grep <id>
to see where the volume is mounted. That's
/var/lib/docker/devicemapper/mnt/<id>/rootfs/
for me, but it might be a different path depending on the OS and configuration. Now simply copy files to that path.
Using -v is not always practical.
Try docker cp.
Usage:
docker cp CONTAINER:PATH HOSTPATH
It copies files/folders from PATH to the HOSTPATH.

Resources