Docker Configuration
This section outlines the Docker configuration used within the development environment for benhall/golang-demo
.
Building the Docker Image
The Dockerfile leverages a two-stage build process to optimize the resulting image size:
Stage 1: Builder Stage
- This stage utilizes the
golang:1.21-alpine
base image. - The working directory is set to
/app
. - The
go.mod
andgo.sum
files are copied into the container. - Dependencies are downloaded and the
go.sum
file is updated. - The entire application code is copied to the container.
- The application is built using
go build -o myapp
.
# First stage: build the application FROM golang:1.21-alpine AS builder # Set the working directory WORKDIR /app # Copy go.mod COPY go.mod go.sum ./ # Download dependencies and generate go.sum RUN go mod download && go mod tidy # Copy the rest of the application code COPY . . # Build the application RUN go build -o myapp
- This stage utilizes the
Stage 2: Runtime Stage
- This stage utilizes the
alpine:latest
base image. - The working directory is set to
/root/
. - The built application binary (
myapp
) is copied from the builder stage. - The container exposes port
8080
to the outside world. - The
CMD
instruction specifies the command to run the executable:./myapp
.
# Second stage: create the runtime image FROM alpine:latest # Set the working directory WORKDIR /root/ # Copy the built application from the builder stage COPY --from=builder /app/myapp . # Expose port 8080 to the outside world EXPOSE 8080 # Command to run the executable CMD ["./myapp"]
- This stage utilizes the
To build the Docker image, navigate to the project root directory and run the following command:
docker build -t golang-demo .
Running the Docker Image
Once the image is built, it can be run with the following command:
docker run --name=golang-http-demo -p 8082:8080 -itd golang-demo
This command:
- Creates a container named
golang-http-demo
. - Maps port
8082
on the host machine to port8080
inside the container. - Runs the container in detached mode (
-d
) and starts an interactive terminal (-it
).
Testing the Application
To test the application running in the container, you can use curl
:
curl localhost:8082
This command will send a request to the localhost:8082
endpoint and display the response, which should be “Hello, World!”.