48
loading...
This website collects cookies to deliver better user experience
850mb
to just 15mb
!├── main.go
├── go.mod
└── go.sum
main.go
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
response := map[string]string{
"message": "Hello Docker!",
}
json.NewEncoder(rw).Encode(response)
})
log.Println("Server is running!")
http.ListenAndServe(":4000", router)
}
Dockerfile
FROM golang:1.16.5 as development
# Add a work directory
WORKDIR /app
# Cache and install dependencies
COPY go.mod go.sum ./
RUN go mod download
# Copy app files
COPY . .
# Install Reflex for development
RUN go install github.com/cespare/reflex@latest
# Expose port
EXPOSE 4000
# Start app
CMD reflex -g '*.go' go run api.go --start-service
docker-compose.yml
. Here we'll also mount our code in a volume so that we can sync our changes with the container while developing.version: "3.8"
services:
app:
container_name: app-dev
image: app-dev
build:
context: .
target: development
volumes:
- .:/app
ports:
- 4000:4000
docker-compose up
-d
flag to run in daemon modeapp-dev | Starting service...
app-dev | 2021/07/04 12:50:06 Server is running!
docker images
commandREPOSITORY TAG IMAGE ID CREATED SIZE
app-dev latest 3063740d56d8 7 minutes ago 872MB
850mb
for a hello world! While this might be okay for development, but for production let's see how we can reduce our image sizeDockerfile
by adding a builder
and production
stageCGO_ENABLED 0
with ENV
in Dockerfile
rather than doing directly before go build
command. Also, we will be using alpine
instead of scratch
as it's really hard to debug containers in production with scratch
FROM golang:1.16.5 as builder
# Define build env
ENV GOOS linux
ENV CGO_ENABLED 0
# Add a work directory
WORKDIR /app
# Cache and install dependencies
COPY go.mod go.sum ./
RUN go mod download
# Copy app files
COPY . .
# Build app
RUN go build -o app
FROM alpine:3.14 as production
# Add certificates
RUN apk add --no-cache ca-certificates
# Copy built binary from builder
COPY --from=builder app .
# Expose port
EXPOSE 4000
# Exec built binary
CMD ./app
docker build -t app-prod . --target production
docker images
~15mb
!!REPOSITORY TAG IMAGE ID CREATED SIZE
app-prod latest ed84a3896251 50 seconds ago 14.7MB
80
docker run -p 80:4000 --name app-prod app-prod
Makefile
to make our workflow easierdev:
docker-compose up
build:
docker build -t app-prod . --target production
start:
docker run -p 80:4000 --name app-prod app-prod