How to set an environment variable in a running docker container

前端 未结 11 1156
难免孤独
难免孤独 2020-11-29 23:28

If I have a docker container that I started a while back, what is the best way to set an environment variable in that running container? I set an environment variable initia

11条回答
  •  無奈伤痛
    2020-11-30 00:02

    Here's how you can modify a running container to update its environment variables. This assumes you're running on Linux. I tested it with Docker 19.03.8

    Live Restore

    First, ensure that your Docker daemon is set to leave containers running when it's shut down. Edit your /etc/docker/daemon.json, and add "live-restore": true as a top-level key.

    sudo vim /etc/docker/daemon.json
    

    My file looks like this:

    {
        "default-runtime": "nvidia",
        "runtimes": {
            "nvidia": {
                "path": "nvidia-container-runtime",
                "runtimeArgs": []
            }
        },
        "live-restore": true
    }
    

    Taken from here.

    Get the Container ID

    Save the ID of the container you want to edit for easier access to the files.

    export CONTAINER_ID=`docker inspect --format="{{.Id}}" `
    

    Edit Container Configuration

    Edit the configuration file, go to the "Env" section, and add your key.

    sudo vim /var/lib/docker/containers/$CONTAINER_ID/config.v2.json
    

    My file looks like this:

    ...,"Env":["TEST=1",...
    

    Stop and Start Docker

    I found that restarting Docker didn't work, I had to stop and then start Docker with two separate commands.

    sudo systemctl stop docker
    sudo systemctl start docker
    

    Because of live-restore, your containers should stay up.

    Verify That It Worked

    docker exec  bash -c 'echo $TEST'
    

    Single quotes are important here.

    You can also verify that the uptime of your container hasn't changed:

    docker ps
    

提交回复
热议问题