Created
March 27, 2019 01:42
-
-
Save alexrios/5fb64bd28320f4a3fa42368814896a64 to your computer and use it in GitHub Desktop.
Safe Multistage build for Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Versão do go que sera utilizada | |
# Default to Go 1.11 | |
ARG GO_VERSION=1.11 | |
# Criando executavel | |
FROM golang:${GO_VERSION}-alpine AS builder | |
#Cria o usuario e grupo que serao usados no container sendo executado para | |
#rodar o processo como um usuario sem privilegio. | |
#https://sobrelinux.info/questions/913/what-is-the-purpose-of-the-nobody-user | |
RUN mkdir /user && \ | |
echo 'nobody:x:65534:65534:nobody:/:' > /user/passwd && \ | |
echo 'nobody:x:65534:' > /user/group | |
# Instala os certificados Certificate-Authority para a App poder fazer chamadas HTTPS | |
# Precisa de Git para fazer o fetching das dependencias. | |
RUN apk add --no-cache ca-certificates git | |
# Configurando a execução do diretorio para fora do $GOPATH para habilitar o suporte a modulos (go mod) | |
WORKDIR /src | |
# Baixa as dependencias; não deve mudar para cada build, | |
# portanto irá fazer cache e otimizar os proximos builds. | |
COPY ./go.mod ./go.sum ./ | |
RUN go mod download | |
# Importa o código do contexto | |
COPY ./ ./ | |
# Build the executable to `/app`. Mark the build as statically linked. | |
# Build do binario em `/app`. Marca o build como linkado estaticamente. | |
RUN CGO_ENABLED=0 go build \ | |
-installsuffix 'static' \ | |
-o /app . | |
# O container que vai executar | |
FROM scratch AS final | |
# Importa o grupo/usuario do primeiro estagio. | |
COPY --from=builder /user/group /user/passwd /etc/ | |
# Importa o Certificate-Authority para habilitar HTTPS. | |
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ | |
# Importa o binario | |
COPY --from=builder /app /app | |
# Declara a porta no qual sera exposta. (usuario sem privilegio não podem fazer bind em portas baixas[1024]) | |
EXPOSE 8080 | |
# Executa as proximas acoes com o usuario sem privilegios | |
USER nobody:nobody | |
# Executando o binario. | |
ENTRYPOINT ["/app"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment