'Run script in container from docker compose?
Trying to install some small packages into a container via compose w/out resorting to having to use my own dockerfile
, but whether I try mounting just the folder, and calling the script, like:
volumes:
- '/opt/docker/configs/extras:/home'
command:
- 'bash /home/install-extra-stuff.sh'
or mounting the file directly and calling it, like:
volumes:
- '/opt/docker/configs/extras/install-extra-stuff.sh:/home/install-extra-stuff.sh'
command:
- 'bash /home/install-extra-stuff.sh'
I get an error that the file doesn't exist
ifelse: fatal: unable to exec bash /home/install-extra-stuff.sh: No such file or directory today at 6:10 PM [cmd] bash /home/install-extra-stuff.sh exited 127
The script itself contains:
#!/bin/bash
# Ping
apt-get update && apt install iputils-ping -y
Hopping into the container itself and running those commands after it has started with those lines above commented out, installs the package just fine.
Any ideas (other than use a dockerfile
?)
Solution 1:[1]
When command
is run in docker-compose.yml
it is passed to the image as sh -c command
so if command is the string 'bash /home/install-extra-stuff.sh'
, this will not be properly parsed by the shell.
I'd suggest instead removing the bash
if that's an option:
command:
- /home/install-extra-stuff.sh
or if you can convert your docker-compose to using version 3 syntax:
command: ["bash", "/home/install-extra-stuff.sh"]
Here are minimal examples that properly ran the test script script.sh
when running docker-compose up --build
.
Default Syntax
services:
test:
build: .
volumes:
- /home/test/script.sh:/script.sh
command:
- /script.sh
Version 3 Syntax
version: "3"
services:
test:
build: .
volumes:
- /home/test/script.sh:/script.sh
command: ["/bin/sh", "/script.sh"]
Solution 2:[2]
presumably this container is going to do something other than just install some packages and terminate, isn't it? If that's the case, you're going to be much better off using a dockerfile and building the image the way you want it and then using that new image in your compose file.
Running a script to install packages as your command:
in the compose file may not work if the image already has an ENTRYPOINT defined, and even if you get it to work, the install script will run and then the container will terminate when it's done.
Solution 3:[3]
That's my suggestion:
services:
replicaset-setup:
container_name: replicaset-setup
image: mongo:4.4.4
restart: "no"
# option 1:
# entrypoint: [ "bash", "-c", "sleep 20 && /scripts/setup.sh" ]
# option 2:
command: bash -c "
sleep 20 &&
chmod +x /scripts/setup.sh &&
scripts/setup.sh"
volumes:
- ./rs-script/setup.sh:/scripts/setup.sh
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | tentative |
Solution 2 | mayostard |
Solution 3 | GtdDev |