How do you stop a service?

I have a pipeline that creates a seeded MySQL image. I define a MySQL database in services: with an explicit data volume, and have steps that (1) run Liquibase against it, and (2) create a new MySQL image that copies out the data volume into the new image. The setup usually works well.

The problem is that on occasion, because the MySQL service is still running when the volume is copied, the data that’s copied into the new image has transient state that breaks the new image. (Think locks, etc.) The solution is to explicitly stop the MySQL service before copying data from the volume.

We’ve explored a few ways to do this, such as issuing a MySQL-specific shutdown command or stopping the container. Which led me to a more general question; what’s the best way to explicitly stop a service? We could just docker ps, find the container ID, and docker stop it, but if there are multiple MySQL containers running on the machine, we might stop the wrong one. And we can’t make the service name dynamic to make it unambiguous, e.g. mysql-$DRONE_BUILD_NUMBER, because the service name is derived from the step name, and the step name doesn’t support variable interpolation.

Any ideas on a clean way to stop a service?