Controlling docker in golang
So meta
- tags
- golang
- docker
Contents
I've been thinking about running different ephemeral jobs with attached volumes, volumes that I could garbage collect as needed. This is a non-standard way of using docker, but I wanted to look to see how I could interact with the docker daemon programatically.
The use case is:
- Create a docker volume for a container
- Start up a docker container, with a specified environment
- Monitor the running of the container, kill if its running for too long
- Capture the output of the container
- Clean up the container
- Pull data from the volume
- Clean up the volume
Setting up go environemnt
First we need to setup a go project and create the go.mod file.
| |
Then we can add the modules that we'll need. In our case, our go.mod file should look like:
| |
And we can get those modules by
| |
This will create a go.sum file that is basically your dependancies.
Our types
We are going to build a simple controller type to hang our methods off
of. Create a types.go file:
| |
Images
| |
Then create a simple test in images_test.go:
| |
We can run the test with:
| |
{"status":"Pulling from library/alpine","id":"latest"}
{"status":"Digest: sha256:69e70a79f2d41ab5d637de98c1e0b055206ba40a8145e7bddb55ccc04e13cf8f"}
{"status":"Status: Image is up to date for alpine:latest"}
PASS
ok dockeringo 0.685s
This makes sure that we have the image we want to run on our machine.
Container logs
Let's write a simple way to get the logs of a container. We won't write a test for this here, since we need to write the container run examples first.
container_log.go:
| |
Running a container
container_run.go:
| |
Now we can write a test to see if everything is running:
container_run_test.go:
| |
And the run the test:
| |
PASS ok dockeringo 1.414s
I'm not saying that it's a great test, but it does test something!
Volumes
Containers have volumes, lets look at how to create them:
volumes.go:
| |
And lets write some tests:
volumes_test.go:
| |
And now we can run the tests:
| |
PASS ok dockeringo 3.245s
Testing persisent volumes
Lets first create a simple script that will look for a file, and if it finds it prints it out and exits with a success. If it doesn't find it, it created it with the current date, prints it out, and exits with a failure.
Call this script.sh:
| |
Now lets create a Dockerfile that runs this:
| |
And we'll build this with
| |
Now lets create a persistent_volume_test.go file, where we will
- Create a volume
- Start the
testimagecontainer with the volume mounted - Run it a second time
- Make sure that the output is the same
- Remove the volume
| |
And now, lets run it:
| |
PASS ok dockeringo 4.186s
Final thoughts
Docker is cool.
Previously
Next