0

Automatically restarting Docker containers

One of the problems that I’ve encountered since moving my Dev/QA departments to using SQL Server within containers is that the host machine is now a single point of failure.

Now there’s a whole bunch of posts I could write about this but the one point I want to bring up now is…having to start up all the containers after patching the host.

I know, I know…technically I shouldn’t bother. After patching and bouncing the host, the containers should all be blown away and new ones deployed. But this is the real world and sometimes people want to retain the container(s) that they’re working with.

I have found it best practice to stop all containers before restarting the host (with the docker stop command) and then starting them back up (with the docker start command) once the host has come online.

However I need not have bothered! Docker gives you the option of setting a restart policy for your containers with the following options: –

  • no: Never automatically restart (the default)
  • on-failure: Restart if there’s been an issue which isn’t critical
  • unless-stopped: Restart unless Docker stops or is explicitly stopped
  • always: Always restart unless explicitly stopped

Let’s run through a quick test using Docker on Windows Server 2016. First let’s run a container: –

docker run -d -p 15789:1433 --restart always --env ACCEPT_EULA=Y --env SA_PASSWORD=Testing1122 --name testcontainer microsoft/mssql-server-windows

docker ps

I’ve used the always option here, so Docker won’t restart my container, but what happens when I bounce the server?

restart-computer -force

Wait for the server to restart and then I can compare system uptime to container uptime: –

$wmi = Get-WmiObject -Class Win32_OperatingSystem
$wmi.ConvertToDateTime($wmi.LocalDateTime) - $wmi.ConvertToDateTime($wmi.LastBootUpTime)

docker ps

N.B. – code to check system uptime is from here

From the above screen shot I can see that the server came up ~6 mins ago and the container came up ~4 mins ago. OK, there’s a bit of a delay there (probably due to the host OS booting, my Azure VMs aren’t really high spec) but the container has come up automatically! So with this switch there’s no need to have to manually start up all the containers on the host.

I’d recommend specifying this switch for all containers if they are being used for active development as this would be pretty handy if there was ever a case of an unexpected host reboot. I don’t want to have to be running start commands whilst a load of developers are waiting for their SQL instances to spin up 🙂

Thanks for reading!