Running a random quotes container

For the subsequent sections of this chapter, we need a container that runs continuously in the background and produces some interesting output. That's why, we have chosen an algorithm that produces random quotes. The API that produces those free random quotes can be found at https://talaikis.com/random_quotes_api/.

Now the goal is to have a process running inside a container that produces a new random quote every five seconds and outputs the quote to STDOUT. The following script will do exactly that:

while : 
do 
    wget -qO- https://talaikis.com/api/quotes/random 
    printf 'n' 
    sleep 5 
done 

Try it in a Terminal window. Stop the script by pressing Ctrl+ C. The output should look similar to this:

{"quote":"Martha Stewart is extremely talented. Her designs are picture perfect. Our philosophy is life is messy, and rather than being afraid of those messes we design products that work the way we live.","author":"Kathy Ireland","cat":"design"}
{"quote":"We can reach our potential, but to do so, we must reach within ourselves. We must summon the strength, the will, and the faith to move forward - to be bold - to invest in our future.","author":"John Hoeven","cat":"faith"}

Each response is a JSON-formatted string with the quote, its author, and its category.

Now, let's run this in an alpine container as a daemon in the background. For this, we need to compact the preceding script into a one-liner and execute it using the /bin/sh -c "..." syntax. Our Docker expression will look as follows :

$ docker container run -d --name quotes alpine \
/bin/sh -c "while :; do wget -qO- https://talaikis.com/api/quotes/random; printf '\n'; sleep 5; done"

In the preceding expression, we have used two new command-line parameters, -d and --name. The -d tells Docker to run the process running in the container as a Linux daemon. The --name parameter in turn can be used to give the container an explicit name. In the preceding sample, the name we chose is quotes.

If we don't specify an explicit container name when we run a container, then Docker will automatically assign the container a random but unique name. This name will be composed of the name of a famous scientist and and adjective. Such names could be boring_borg or angry_goldberg. Quite humorous our Docker engineers, isn't it?

One important takeaway is that the container name has to be unique on the system. Let's make sure that the quotes container is up and running:

$ docker container ls -l 

This should give us something like this:

Listing the last run container

The important part of the preceding output is the STATUS column, which in this case is Up 16 seconds. That is, the container has been up and running for 16 seconds now.

Don't worry if the last Docker command is not yet familiar to you, we will come back to it in the next section.