Search code examples
dockercontainers

How to edit a file inside a docker container


What we want to achieve: We have downloaded a docker container called smokeping and want to edit a file within permanently. We want to have a file called smokeping-new that i can deploy to dozens of switches. They run the file and should have the changes already presented within. So what i have done:

Download the docker, run the docker, start a bash within this docker and edit the file with VI, save the changes, make sure the changes are saved within the file by opening it again and verifying with VI.

Then, i issue the command Docker PS:

PS C:\Users\admin> docker ps
CONTAINER ID   IMAGE                   COMMAND   CREATED          STATUS          PORTS     NAMES
c6fd5995f25e   smokeping   "/init"   11 minutes ago   Up 11 minutes   80/tcp    sweet_gates

Then commit to create a new docker image with the command:

docker container commit c6fd5995f25e smokping-new

Then stop the container and show all the images available:

PS C:\Users\admin> docker images
REPOSITORY                    TAG       IMAGE ID       CREATED              SIZE
smokeping-new                 latest    6666728dfa41   About a minute ago   253MB
smokeping                     latest    6ed653a69e5d   28 hours ago         253MB
jwigley/smokeping-speedtest   latest    4f12ea8b5fce   13 days ago          253MB
nginx                         latest    eea7b3dcba7e   2 weeks ago          187MB
networkstatic/iperf3          latest    f2633a30407f   5 weeks ago          81.8MB

Then export the newly created docker image with:

docker save --output smokeping-new.tar smokeping-new

But the changes to the file are not within the image if we run the new docker locally on the PC or on the switch. How can i get a new docker with my changes saved? I dont have a github so the docker build command might not work for me. i just want to have a local copy of my new Docker file that i can deploy.


Solution

  • There are two ways to do that:

    1. Rebuild the container with your file added

    (persist over container instances, but not updates)

    # Dockerfile
    FROM smokeping-new
    COPY ./myfile/on/pc.json ./myfile/in/container.json
    
    # docker-compose.yaml
    version: '3.8'
    services:
      smokeping-new:
        image: my.repo.com/smokeping-new:my-tag
    
    # command
    docker compose build smokeping-new
    docker push my.repo.com/smokeping-new:my-tag
    

    2. Mount your file

    (presist over container updates, but not instances)

    # docker-compose.yaml
    version: '3.8'
    services:
      smokeping-new:
        image: smokeping-new:latest # updates allowed
        volumes:
          - ./myfile/on/pc.json:./myfile/in/container.json