Sometimes it's helpful to run a container inside GitHub Actions, like if you want to run something isolated from the rest of the CI environment for one step. Docker already exists (at least on the Ubuntu runners), so we can just ahead and use it.
We could do this directly in the YAML, but extracting out to a script is helpful, especially so if you want to interact with the container itself. But you could also do a multiline string, or similar if desired.
For example, you might have a script like this:
#!/bin/sh
set -e
run_in_container() {
container_id=$1
shift
cmd=$*
docker exec --workdir /app "$container_id" bash -c "$cmd"
}
echo "Starting container using Ruby 3.2.2..."
container_id=$(
docker run \
-d -v .:/app ruby:3.2.2 sleep infinity
)
echo "Run bundle install..."
run_in_container "$container_id" "bundle install"
echo "Tidying up container..."
docker stop "$container_id" > /dev/null
docker rm "$container_id" > /dev/nullThis can just be run as any other run step.
There's a few gotchas to be aware of though:
- You can pass through already defined environment variables with
--env PGHOST - Unlike running locally, it's not run with a TTY, so don't add
--ttyto eitherexecorrun - If you want to talk to other services (like Postgres), add
--network "host"todocker run - Docker containers almost always run as root, so you may subsequently need to do something like:
sudo chown -R $(whoami)outside of the container, if you get permissions issues from a mounted volume