Docker Build, Test and Deploy#

In this lab you’ll build a customized container based on Apache. On your local machine you’ll verify that the container has been created and when you’re satisfied you’ll push it to a container repository.

The Dockerfile#

A Dockerfile is a recipe for building a container. It begins with a base container to start from. This Dockerfile starts with the basic Apache2 container and simply adds a custom index.html from the current directory.

FROM docker.io/httpd

COPY index.html /usr/local/apache2/htdocs/index.html

The Dockerfile copies a file called index.html into the web root of the container. Create an index.html next to the Dockerfile with your name and a message in it.

Build#

With the recipe and supporting files you can build the container:

$ docker build -t hello-http . 

Test#

This command will run your container in the foreground (-i) so it’s easy to quit using Ctrl-c. It will delete the container after it stops (--rm) which saves a step later.

$ docker run -i --rm -p 8080:80 hello-http 

You should be able to direct your browser to http://localhost:8080/ and see the running container. If you’re using a VM for development use the Ports feature of vscode to forward a port.

Tag and Push#

Can you see your name? That means your container has been built properly and is ready for production. Before it can be published to the cloud it has to be pushed from your computer to your Google registry. First tag the image with the registry name you got in the previous lab:

$ docker tag hello-http us-central1-docker.pkg.dev/project-name/repo-name/hello-http

The tag identifies where the image belongs. Now push the image:

$ docker push us-central1-docker.pkg.dev/project-name/repo-name/hello-http

Depending on your internet connection the push may take a while.

Deploy#

Now that the container image is in the registry you can deploy it using a VM. If you were to do it manually the steps would generally be:

  1. Create a VM with Linux

  2. Install Docker on the VM

  3. Run the container using Docker (using docker run)

Creation and installation of the VM could be done with Terraform and Ansible or by hand. But even with some automation the process would be a bit tedious if we’re only deploying one container. Google has a container optimized Linux that will automatically start one container at boot time. Here’s how to use gcloud to create a VM and start a container in one command:

$ gcloud compute instances create-with-container hello-http --machine-type=e2-micro --container-image=us-central1-docker.pkg.dev/project-name/repo-name/hello-http --tags=http-server

Note

Take a screenshot of the deployed container.

Clean Up#

The e2-micro machine will cost you about $8 per month to operate continuously. It’s a low-resource machine that’s fine for this simple workload. But, you should delete it once you’re done with the lab so you don’t rack up unnecessary charges.

$ gcloud compute instances delete hello-http