As we know, services are made up of source code and configurations. A service written in Java, for instance, can be packaged as a Java Archive (JAR) file containing compiled class files in Java bytecode, as well as resources such as configuration and properties files. Once packaged, the JAR file can then be executed on any machine running a Java Virtual Machine (JVM).
In order for this to work, however, the machine that we want to run our service on must have a JVM installed. Oftentimes, it must be a specific version of the JVM. Additionally, the machine might need to have some other utilities installed, or it might need access to a shared filesystem. While these are not parts of the service themselves, they do make up what we refer to as the runtime environment of the service.
Linux containers are a technology that allow developers to package an application or service with its complete runtime environment. Containers separate out the runtime for a particular application from the runtime of the host machine that the container is running on.
This makes applications more portable, making it easier to move a service from one environment to another. An engineer can run a service on their laptop, then move it into a preproduction environment, and then into production, without changing the container itself. Containers also allow you to easily run multiple services on the same machine, therefore allowing much more flexibility in how application architectures are deployed and providing opportunities for operational cost optimization.
Docker is a container runtime and set of tools that allows you to create self-contained execution environments for your service. There are other popular container runtimes they are widely used today, but Docker is designed to make containers portable and flexible, making it an ideal choice for building containers for services.
In this recipe, we'll use Docker to create an image that packages our message-service. We'll do this by creating a Dockerfile file and using the Docker command-line utility to create an image and then run that image as a container.