Skip to content

Instantly share code, notes, and snippets.

@nickcharlton
Created January 13, 2025 17:15
Show Gist options
  • Save nickcharlton/93007b00d595ced4301f867a3931edb0 to your computer and use it in GitHub Desktop.
Save nickcharlton/93007b00d595ced4301f867a3931edb0 to your computer and use it in GitHub Desktop.
Gist from Drafts

Running Docker containers on GitHub Actions

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/null

This 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 --tty to either exec or run
  • If you want to talk to other services (like Postgres), add --network "host" to docker 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment