Docker Golang
again this is for my self reference or for easy copy-paste for new projects.
Assume this is the production grade program we need to dockerize and run.
package main
import "fmt"
func main() {
fmt.Println("saying hello to the world")
}
Basic
#-NAME: Dockerfile multistage build
FROM golang:1.14-alpine as builder
WORKDIR /go/src/github.com/shabinesh/prog
COPY main.go .
COPY vendor ./vendor
RUN go build -o main .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /
COPY --from=0 /go/src/github.com/shabinesh/prog/main .
CMD ["./main"]
If the service depends on private repositor
- set the `GOPRIVATE`
- Update the git to include github token (in this case)
FROM golang:1.14-alpine AS builder
ARG GITHUB_TOKEN
WORKDIR /go/src/github.com/my-org/hello-service
RUN apk add --update bash make git curl ca-certificates
# Patch git to use a private token if one was provided
RUN if [ ! -z "${GITHUB_TOKEN}" ]; then \
git config --global --add url."https://${GITHUB_TOKEN}@github.com/my-org/".insteadOf "git@github.com:my-org/" && \
git config --global --add url."https://${GITHUB_TOKEN}@github.com/my-org/".insteadOf "https://github.com/my-org/" && \
git config --global --add url."https://${GITHUB_TOKEN}@github.com/my-org/".insteadOf "https://git@github.com/my-org/"; \
fi
RUN go mod vendor
RUN go build -o main .
docker-compose with service and postgres
version: "3.0"
services:
hello-service:
build:
context: .
dockerfile: Dockerfile.dev
args:
- GITHUB_TOKEN
environment:
SERVER_PORT: 80
volumes:
- .:/go/src/github.com/my-org/hello-service
command: "CompileDaemon -build='make build' -command='./build/hello-service'"
ports:
- "8000:80"
depends_on:
- postgres
postgres:
image: postgres:12
ports:
- "5432:5432"
environment:
POSTGRES_USER: app_user
POSTGRES_PASSWORD: app_password
POSTGRES_DB: hello_service
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ca"]
retries: 3