I am attempting to run my docker container in my linux server and configure it as a systemd unit to manage itself. My /etc/systemd/system/system.service file features this line:
[Unit]
Description=Your Container Name
After=docker.service
Requires=docker.service
StartLimitInterval=200
StartLimitBurst=10
[Service]
TimeoutStartSec=0
Restart=always
RestartSec=2
ExecStartPre=-/usr/bin/docker exec %n stop
ExecStartPre=-/usr/bin/docker rm %n
ExecStartPre=/usr/bin/bash -c 'docker login -u AWS -p $(aws ecr get-login-password --region eu-west-1) 0123456789.dkr.ecr.eu-west-1.amazonaws.com'
ExecStartPre=/usr/bin/docker pull 0123456789.dkr.ecr.eu-west-1.amazonaws.com/your-container:latest
ExecStart=/usr/bin/docker run --rm --name %n 0123456789.dkr.ecr.eu-west-1.amazonaws.com/your-container:latest -e env_var1=abc -e env_var2=def
[Install]
WantedBy=multi-user.target
This has proven problematic because when I restart the service and check the status it shows this error:
● docker.name.service - name
Loaded: loaded (/etc/systemd/system/docker.name.service; disabled; vendor preset: disabled)
Active: failed (Result: start-limit) since Thu 2022-03-10 19:28:06 UTC; 6min ago
Process: 11029 ExecStart=/usr/bin/docker run --rm --name %n 0123456789.dkr.ecr.eu-west-1.amazonaws.com/your-container:latest -e env_var1=abc -e env_var2=def (code=exited, status=127)
Process: 11018 ExecStartPre=/usr/bin/docker pull 0123456789.dkr.ecr.eu-west-1.amazonaws.com/your-container:latest (code=exited, status=0/SUCCESS)
Process: 10984 ExecStartPre=/usr/bin/bash -c docker login -u AWS -p $(aws ecr get-login-password --region eu-west-1) 0123456789.dkr.ecr.eu-west-1.amazonaws.com/your-container:latest (code=exited, status=0/SUCCESS)
Process: 10973 ExecStartPre=/usr/bin/docker rm %n (code=exited, status=1/FAILURE)
Process: 10951 ExecStartPre=/usr/bin/docker exec %n stop (code=exited, status=1/FAILURE)
Main PID: 11029 (code=exited, status=127)
Process: 8174 ExecStart=/usr/bin/docker run --rm --name %n 0123456789.dkr.ecr.eu-west-1.amazonaws.com/your-container:latest -e env_var1=abc -e env_var2=def (code=exited, status=127)
Removing the docker -e options env_var1=abc -e env_var2=def and restarting the service then allows the service to start correctly. How do I get these environment variables to be passed to the docker container from the service? It is critical they are.
CodePudding user response:
docker run considers everything after the image name to be a command that's passed to the container, overriding whatever is configured in the Dockerfile with CMD
.
To provide environment variables to the container itself, your -e
options need to appear before the image name:
ExecStart=/usr/bin/docker run --rm --name %n -e env_var1=abc -e env_var2=def 0123456789.dkr.ecr.eu-west-1.amazonaws.com/your-container:latest