How to edit a file dynamically in a running docker container

8.3k Views Asked by At

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.

enter image description here 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
3

There are 3 best solutions below

2
On BEST ANSWER

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
1
On

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!

0
On

you just need to mount the folder using -v as an option. i give an example

  1. let's say i have /home/awan/config.yml <--- this file is always dynamic must not put it inside container

  2. 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

  1. 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