< Docker

Dockerfile

# Configures a Go web server and copies the current folder content
# to use as server root.

# Use the following commands to build and run the server.
#   docker build -t go-server .
#   docker run -d -p 8000:8000 --name=go-server go-server

# Then open a web browser and connect to http://localhost:8000 .

# References:
#   https://blog.logrocket.com/creating-a-web-server-with-golang/

#build stage
FROM golang:alpine AS builder
RUN apk add --no-cache git
WORKDIR /go/src/app
COPY . .
RUN go get -d -v ./...
RUN go install -v ./...

#final stage
FROM alpine:latest
RUN apk --no-cache add ca-certificates
COPY --from=builder /go/bin/app /app
ENTRYPOINT ./app

EXPOSE 8000

server.go

// Displays "Hello world!"
//
// References:
//  https://repl.it/@mauriycf/A-simple-web-server-in-go#main.go
//  https://gowebexamples.com/hello-world/

package main

import (
    "net/http"
    "io"
)

func handler(response http.ResponseWriter, request *http.Request) {
    io.WriteString(response, "Hello world!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8000", nil)
}

Try It

Online Free

  1. Use Play with Docker. Create an account and/or log in.
  2. Start an interactive session and add a new instance.
  3. In the terminal window, enter the following commands:
    • touch Dockerfile
    • touch server.go
  4. Use the Editor button to edit both files and save the contents above into each respective file.
  5. Run the following commands:
    • docker build -t go-server .
    • docker run -d -p 8000:8000 --name=go-server go-server
  6. In the top window, select the 8000 button to connect to the running server.

On Your Own System

  1. Install Docker Desktop or the Docker Engine.
  2. Save the files above into a new Docker Flask folder:
    • Dockerfile
    • server.go
  3. At a command prompt, change to the Docker Flask folder and then run the following commands:
    • docker build -t go-server .
    • docker run -d -p 8000:8000 --name=go-server go-server
  4. Open a web browser to connect to the running server:

See Also

This article is issued from Wikiversity. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.