Manage a Docker container on an Ubuntu VM with Cloud-Init

There are times when you might want to host a Docker container but a managed app service isn’t sufficient and a full blown Kubernetes cluster would be overkill.

For a situation like this, hosting the container on a standard Virtual Machine could be just the solution. It’s an extremely easy and lightweight to bootstrap the virtual machine with Cloud-Init which might normally be done with a tool like Ansible or Chef.



Accomplishing this is 3 basic steps:

  • Install Docker
  • Create a systemd service file
  • Start and Enable the container service

#cloud-config

apt:
  sources:
    docker.list:
      source: deb [arch=amd64] https://download.docker.com/linux/ubuntu $RELEASE stable
      keyid: 9DC858229FC7DD38854AE2D88D81803C0EBFCD88

packages:
  - docker-ce
  - docker-ce-cli

write_files:
  - path: /etc/systemd/system/container.service
    owner: root:root
    permissions: '0755'
    content: |
        [Unit]
        Description=Run container
        Requires=docker.service
        After=docker.service

        [Service]
        Restart=always
        ExecStartPre=-/usr/bin/docker rm container
        ExecStart=/usr/bin/docker run --rm --name container hello-world
        ExecStop=/usr/bin/docker stop -t 2 container        

runcmd:
  - systemctl start container
  - systemctl enable container

Thank you

Your comment has been submitted and will be published once it has been approved.

OOPS!

Your comment has not been submitted. Please go back and try again. Thank You!

If this error persists, please open an issue by clicking here.

Say something