Docker/Go
< Docker
Dockerfile
edit# 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/
# https://stackoverflow.com
FROM golang:alpine
WORKDIR /usr/src/app
COPY . .
RUN go build app.go
EXPOSE 8000
CMD ["./app"]
app.go
edit// 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
editOnline Free
edit- Use Play with Docker. Create an account and/or log in.
- Start an interactive session and add a new instance.
- In the terminal window, enter the following commands:
touch Dockerfile
touch app.go
- Use the
Editor
button to edit both files and save the contents above into each respective file. - Run the following commands:
docker build -t go-server .
docker run -d -p 8000:8000 --name=go-server go-server
- In the top window, select the
8000
button to connect to the running server.
On Your Own System
edit- Install Docker Desktop or the Docker Engine.
- Save the files above into a new
Docker Go
folder:Dockerfile
app.go
- At a command prompt, change to the
Docker Go
folder and then run the following commands:docker build -t go-server .
docker run -d -p 8000:8000 --name=go-server go-server
- Open a web browser to connect to the running server: