This is a simple tutorial demonstrates creating Golang Docker image.
Prerequisites:
Go App
Create a simple Go program hello-http.go
:
package main
import (
"fmt"
"log"
"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello world\n")
}
func main() {
http.HandleFunc("/", hello)
log.Println("Starting server on 0.0.0.0:8080")
http.ListenAndServe(":8080", nil)
}
Docker file
In the same directory, create Docker manifest file (Dockerfile
):
# initializes a new build stage and sets the base image
FROM golang:1.15.1-alpine
# copy hello-http.go and add it to the filesystem of the image
ADD hello-http.go .
# compile the program
RUN go build hello-http.go
# provide the default command for the container
CMD ["/go/hello-http"]
docker build
Build an image from your Dockerfile
$ docker build . -t hello:v1.0.0
-
-t
Name and tag the image in the 'name:tag' format
List docker images:
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
hello v1.0.0 47f0babcdfe2 44 minutes ago 306MB
run the command:
$ docker run -dit --rm -p 8080:8080 --name hello hello:v1.0.0
-
docker run
Run a command in a new container -
-d
Run container in background and print container ID -
-i
interactive -
-t
Allocate a pseudo-TTY -
--rm
Automatically remove the container when it exits -
-p 8080:8080
Publish a container's port(s) to the host -
hello:v1.0.0
Docker image to run -
--name hello
Assign a name to the container
Test your container
$ docker ps
-
docker ps
List containers
You see a list like this shows a container running hello
image.
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
7c3c8774134d hello:v1.0.0 "/go/hello-http" 54 minutes ago Up 54 minutes 0.0.0.0:8080->8080/tcp hello
Now open your browser and go to http://localhost:8080/
:
End the container
Now run the following command to end the container:
$ docker stop hello
Now list the containers
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
Note that docker container has stopped and automatically removed:
$ docker ps -a
You will see this:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
Top comments (0)