Difficulty: beginner
Estimated Time: 15 minutes

In this section you will dig into some more details of containers and container images

  • What gets built into a container image
  • Getting logs from containers
  • Mounting host directories into containers
  • Passing environment variables into the container

Congratulations, you've finished this scenario! Here's what you have covered:

  • Building a container image containing additional files
  • Mounting directories from the host into the container
  • Stdout and stderr are accessible through the docker logs command
  • Passing environment variables into containers

You have also seen how to use docker ps -q to get running container IDs that you can then pass in to other docker commands.

What's inside a container image?

Step 1 of 6

Write a simple web server

Start by writing a simple Go web server application. This is very similar to the app in the Container basics scenario, but this time the response content is read from a file rather than being hard-coded.

Hello world

Write a basic web server in Go that will respond to a request on port 8080 with a simple message like "hello world". The editor pane on the top right of this screen is already set up to edit a file called hello.go. You can click the button below to copy the code into that file.

package main

import (
  "fmt"
  "io/ioutil"
  "net/http"
  "os"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        response, err := ioutil.ReadFile("./text/response")
        if err != nil {
            fmt.Printf("reading file: %v\n", err)
            os.Exit(1)
        }

        fmt.Printf("response: %s\n", response)
        w.Write(response)
    })

    err := http.ListenAndServe(":8080", nil)
    if err != nil {
      fmt.Printf("serving: %v\n", err)
      os.Exit(1)
    }
}

Compile this app:

CGO_ENABLED=0 go build -o hello hello.go

You'll need to define the response file that this application code reads from. First let's open the file in the editor:

text/response

And copy the message into that text file. (Feel free to change it to make it your own!)

Here's a response

Run your app

Run the app in the background (using the ampersand) so that you can still type into the terminal.

./hello &

Check you get the response you expect when making a request to your application using curl:

curl localhost:8080

You should see

  • the output from the call to fmt.Printf which displays the contents of the response file, and
  • the text message returned to your request.

It should look something like this:

$ curl localhost:8080
response: Here's a response

Here's a response

Stop the application

When you're satisfied that this application works, let's stop it:

kill %1

Next step

At this stage you have a compiled Go binary and a text file that it reads from. In the next step we'll build a container image that includes both the binary and the text file.

hello.go
response
Dockerfile