Deploy docker images manually and via GitHub


Now I will compile a Go application to docker image and deploy to different place.

First I will create a simple application to use for this time.

mkdir docker-deploy
cd docker-deploy
go mod init godocker
touch main.go
package main

import (
	"fmt"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
)

var (
	buildcommit = ""
	buildtime   = ""
)

func main() {
	greeting, name := "Hello", "Albert"
	if v, ok := os.LookupEnv("greeting"); ok {
		greeting = v
	}
	if v, ok := os.LookupEnv("name"); ok {
		name = v
	}
	r := gin.Default()
	r.GET("/", func(ctx *gin.Context) {
		ctx.String(http.StatusOK, fmt.Sprintf("%s, %s!", greeting, name))
	})
	r.GET("/x", func(ctx *gin.Context) {
		ctx.JSON(http.StatusOK, gin.H{
			"buildcommit": buildcommit,
			"buildtime":   buildtime,
		})
	})
	r.Run()
}

Create Dockerfile file and add this

FROM golang:1.17-alpine AS builder
WORKDIR /app
COPY go.mod .
COPY go.sum .
RUN go mod download
COPY . .
RUN go build -ldflags \\
  "-X 'main.buildcommit=$(git log --format="%H" -n 1)' \\
  -X 'main.buildtime=$(date "+%A %W %Y %X")'" \\
  -o app

FROM alpine:latest
WORKDIR /
COPY --from=builder /app/app .
EXPOSE 8080
CMD ["/app"]`}

login to your docker account, compile the docker image and push to docker hub

docker login
docker build -t nuttawut503/mydocker:1.0 .
docker push nuttawut503/mydocker:1.0

please change nuttawut503 to match your docker account.

Next, let's do this in GitHub! Go to your Account Settings in docker hub website, click at Security, generate New Access Token and copy that text. Then move to your GitHub repository, click Settings, go to Secrets -> Actions and click New repository secret; Add two value, DOCKER_HUB_ACCESS_TOKEN (insert the token from docker hub here) and DOCKER_HUB_USERNAME (your username).

Create .github/workflows/release.yml file

name: Build image to docker hub
on:
  push:
    branches:
    - "main"
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout
      uses: actions/checkout@v2
    - name: Login to docker hub
      uses: docker/login-action@v1
      with:
        username: \$\{\{ secrets.DOCKER_HUB_USERNAME \}\}
        password: \$\{\{ secrets.DOCKER_HUB_ACCESS_TOKEN \}\}
    - name: Set up docker buildx
      uses: docker/setup-buildx-action@v1
    - name: Build and push
      uses: docker/build-push-action@v2
      with:
        context: .
        push: true
        tags: \$\{\{ secrets.DOCKER_HUB_USERNAME \}\}/autodocker:latest

Then commit this file to GitHub and see what is gonna happen. Thank you for reading

sources