This guide will cover how to start, stop, and manage Docker containers for the golang-demo project. We will also discuss port mapping and container naming. The Golang Module name for this project is “myapp”, and the Dockerfile exposes Port 8080.
Prerequisites
- Ensure you have Docker installed on your system. You can download Docker from here.
- Familiarize yourself with the official Golang Docker documentation.
Building the Go Image
- Create a
Dockerfile
in the project directory with the following content:
# Use an official Golang runtime as a parent image
FROM golang:1.17-alpine AS build-env
# Set environment variables
ENV APP_NAME myapp
ENV CMD_PATH cmd/main.go
# Copy the local package files to the container's workspace
COPY . $GOPATH/src/$APP_NAME
WORKDIR $GOPATH/src/$APP_NAME
# Install any needed packages specified in go.mod
RUN go mod download
# Build the Go app
RUN CGO_ENABLED=0 go build -a -o /$APP_NAME $CMD_PATH
# Use an Alpine Linux runtime as a base for the production environment
FROM alpine:3.14
# Copy the Go app from the previous stage
COPY --from=build-env /$APP_NAME /$APP_NAME
# Set the default command to execute
ENTRYPOINT ["/myapp"]
- Build the Docker image:
docker build -t myapp .
Running the Docker Container
- Run the Docker container with the following command:
docker run -d --name myapp-container -p 8080:8080 myapp
This command does the following:
-d
: Run the container in detached mode (in the background).--name
: Assign a name to the container for easier management.-p
: Map the container’s port 8080 to the host’s port 8080.
- Verify the container is running:
docker ps
Stopping the Docker Container
- Stop the Docker container with the following command:
docker stop myapp-container
Restarting the Docker Container
- Restart the Docker container with the following command:
docker start myapp-container
Removing the Docker Container
- Remove the Docker container with the following command:
docker rm myapp-container
Additional Resources
- Docker + Golang = <3
- Docker Docs: Golang
- Docker Docs: Run Containers
- Red Hat Developer: Build Your “Hello World” Container Using Go
- Sweetcode.io: Writing Docker Files for Different Technology Stacks
- Chainguard Academy: go Image Overview
- Buildkit & Docker Buildx
- Red Hat Developer: Build lightweight and secure container images using RHEL UBI