Running Docker Containers - benhall/golang-demo

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

Building the Go Image

  1. 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"]
  1. Build the Docker image:
docker build -t myapp .

Running the Docker Container

  1. 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.
  1. Verify the container is running:
docker ps

Stopping the Docker Container

  1. Stop the Docker container with the following command:
docker stop myapp-container

Restarting the Docker Container

  1. Restart the Docker container with the following command:
docker start myapp-container

Removing the Docker Container

  1. Remove the Docker container with the following command:
docker rm myapp-container

Additional Resources