Part 6: Using Docker In Earthly
To copy the files for this example ( Part 6 ) run
earthly --artifact github.com/earthly/earthly/examples/tutorial/go:main+part6/part6 ./part6Examples in Python, JavaScript and Java are at the bottom of this page.
The WITH DOCKER Command
WITH DOCKER CommandYou may find that you need to run Docker commands inside a target. For those cases Earthly offers WITH DOCKER. WITH DOCKER will initialize a Docker daemon that can be used in the context of a RUN command.
Whenever you need to use WITH DOCKER we recommend (though it is not required) that you use Earthly's own Docker in Docker (dind) image: earthly/dind:alpine-3.19-docker-25.0.5-r0.
Notice WITH DOCKER creates a block of code that has an END keyword. Everything that happens within this block is going to take place within our earthly/dind:alpine-3.19-docker-25.0.5-r0 container.
Pulling an Image
hello:
FROM earthly/dind:alpine-3.19-docker-25.0.5-r0
WITH DOCKER --pull hello-world
RUN docker run hello-world
END
You can see in the command above that we can pass a flag to WITH DOCKER telling it to pull an image from Docker Hub. We can pass other flags to load in artifacts built by other targets --load or even images defined by docker-compose --compose. These images will be available within the context of WITH DOCKER's docker daemon.
Loading an Image
We can load in an image created by another target with the --load flag.
A Real World Example
One common use case for WITH DOCKER is running integration tests that require other services. In this case we need to set up a redis service for our tests. For this we can user a docker-compose.yml.
docker-compose.yml
main.go
main_integration_test.go
When we use the --compose flag, Earthly will start up the services defined in the docker-compose file for us. In this case, we built a separate image that copies in our test files and uses the command to run the tests as its ENTRYPOINT. We can then load this image into our WITH DOCKER command. Note that loading an image will not run it by default, we need to explicitly run the image after we load it.
You'll need to use --allow-privileged (or -P for short) to run this example.
More Examples
Last updated
Was this helpful?
