Create a Go(Gin) environment with Docker
at first
We will assume that you already have a Docker environment. Let’s easily create a Go (Gin) environment using Docker.
Create DockerFile
Create a working directory, create [DockerFile] and copy and paste the following
// specify the base Docker image
FROM golang:latest
create a working directory inside the container
RUN mkdir /go/src/work
specify the directory when logging into the container
WORKDIR /go/src/work
Launch GoApp
CMD ["go","run","main.go"]
migrate host files to container working directory
ADD . /go/src/work
create docker-compose.yml
Create a [docker-compose.yml] file in the same directory and copy and paste the following
version: '3' # specify the version of the compose file
services:
app: # service name
build: . # Specify the directory where the Dockerfile used for building is located
tty: true # Container startup persistence
volumes: - .:/go/src/work # Specify mount directory
ports: -8080:8080
Create Go source
Create a [main.go] file in the same directory and copy and paste the following
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>Hello, World</h1>")
}
func main() {
http. HandleFunc("/", helloHandler)
fmt.Println("Server Start")
http.ListenAndServe(":8080", nil)
}
Check if the file exists in the directory by hitting the ls command.
ls DockerFile docker-compose.yml main.go
Command execution with CLI
Hit the following command with git bush (CLI tool).
$ docker-compose build
$ docker-compose up -d
Try visiting http://localhost:8080.