A collection of task oriented solutions in Puppet

 

Run a Docker Container

Challenge

You want to run a Docker container

Solution

class docker_container {

  # include the docker class
  include ::docker

  # fetch the docker image
  ::docker::image { 'nginx':
    ensure    => 'present',
    image_tag => 'stable-alpine',
    require   => Class['docker'],
  }

  # run the container using the image above
  ::docker::run { 'nginx':
    image   => 'nginx:stable-alpine',
    ports   => ['8080:80'],
    require => Docker::Image['nginx'],
  }

}

Explanation

Once you've installed the docker daemon, either accepting the defaults and include ::docker or with customisations you only need to specify two more resources to run a container. The first is the image you want to base the container on:

class docker_container {

  # include the docker class
  include ::docker

  # fetch the docker image
  ::docker::image { 'nginx':
    ensure    => 'present',
    image_tag => 'stable-alpine',
    require   => Class['docker'],
  }

}
# run puppet
Notice: /Stage[main]/Profile::Docker/Docker::Image[nginx]/Exec[/usr/local/bin/update_docker_image.sh
  nginx:stable-alpine]/returns: executed successfully

# once puppet has finished verify the image was downloaded

$ docker images | grep nginx
docker.io/nginx  stable-alpine  501d2ca4f2e2 1 days ago  54.68 MB

The second resource is the container itself and any options you want to run it with:

  ::docker::run { 'nginx':
    image   => 'nginx:stable-alpine',
    # port 8080 on the docker host passes through to port 80 on the container
    ports   => ['8080:80'],
    require => Docker::Image['nginx'],
  }
# run puppet to apply the new ::docker::run resource
... snip ...
Info: /Stage[main]/Profile::Docker/Docker::Run[nginx]/File[/etc/systemd/system/docker-nginx.service]: Scheduling refresh of Service[docker-nginx]
Notice: /Stage[main]/Profile::Docker/Docker::Run[nginx]/Service[docker-nginx]/ensure: ensure changed 'stopped' to 'running'
... snip ...

# run docker to check the container has started
$ sudo docker ps
CONTAINER ID     IMAGE               COMMAND                  CREATED            STATUS
9f8f428ca5d5     nginx:stable-alpine "nginx -g 'daemon off"   22 seconds ago     Up 18 seconds

# and hit the containers exposed port as a final verification
$ curl -s -I 127.0.0.1:8080 | grep Server
Server: nginx/1.10.2

While it's possible to specify many more options to both the docker install and the running container the examples above should provide you with a basic, but full example.

See also