Skip to main content

Docker - Setting Go

Docker - Setting Go

Docker is a strong tool. It helps us automate how we deploy apps inside small and portable containers. When we use Docker with Go, we get a language that is simple and works well. This makes Docker - Setting Go very important for making apps that can grow and are easy to manage. Together, they help us make our work easier. They also help us keep the same settings at different stages of our work.

In this chapter, we will look closely at Docker - Setting Go. We will start with how to install Docker. Then we will create a Go application. After that, we will write a good Dockerfile. We will also learn about building Docker images. We will see how to run Go apps in containers. Lastly, we will use Docker Compose for managing our projects. By the end, we will understand how to use Docker with Go for our development needs.

Introduction to Docker and Go

Docker is a strong tool. It helps developers to automate how we deploy applications in lightweight and portable containers. These containers hold everything an application needs to work. They make sure we have the same environment on different systems. Go, or Golang, is a simple and fast language. It is great for building applications that can grow easily.

When we combine Docker with Go, we get many benefits:

  • Environment Consistency: Docker containers make sure our Go application works the same in development, testing, and production.
  • Isolation: Each Go application runs in its own container. This stops problems between different dependencies.
  • Scalability: Docker helps us to scale Go applications by running many instances in containers.

To begin with Docker - Setting Go, we need to learn how to create a Docker image. This image will package our Go application. We will talk about this in the next sections. If you want to learn more about deploying applications with Docker, you can look at Docker - Setting Node.js and What is Docker.

Installing Docker

To begin using Docker for our Go applications, we need to install Docker on our computer. Docker gives us a steady environment for building, running, and managing containers. This is very important for Go development.

Steps to Install Docker:

  1. Download Docker: We go to the official Docker installation page to download the Docker Desktop app that fits our operating system. This can be Windows, macOS, or Linux.

  2. Installation:

    • Windows/Mac: We run the installer we just downloaded and follow the steps in the installation wizard.
    • Linux:
      • First, we need to update our package index:

        sudo apt-get update
      • Next, we install some needed packages:

        sudo apt-get install \
            apt-transport-https \
            ca-certificates \
            curl \
            software-properties-common
      • Then, we add Docker’s official GPG key:

        curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
      • After that, we add the Docker repository:

        sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
      • Finally, we install Docker:

        sudo apt-get update
        sudo apt-get install docker-ce
  3. Verify Installation: Once we finish the installation, we check if Docker is running:

    docker --version
  4. Post-installation steps (Linux only): If we want to run Docker commands without using sudo, we need to add our user to the Docker group:

    sudo usermod -aG docker $USER

For a better guide, we can check Docker Installation. After we install Docker, we can start creating our Go application and use Docker’s features.

Creating a Go Application

To create a Go application for Docker, we can follow these easy steps:

  1. Set Up Your Go Environment: First, we need to make sure Go is installed on our computer. We can download it from the official Go website.

  2. Create Your Project Directory: We make a new folder for our project. Run these commands:

    mkdir my-go-app
    cd my-go-app
  3. Initialize Your Go Module: This helps us manage our dependencies. We do it with this command:

    go mod init my-go-app
  4. Write Your Go Application: Next, we create a file called main.go in our project folder. Here is what we put in the file:

    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    func handler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, Docker with Go!")
    }
    
    func main() {
        http.HandleFunc("/", handler)
        http.ListenAndServe(":8080", nil)
    }
  5. Test Your Application Locally: Now we run the application to check if it works. We use this command:

    go run main.go

    Then we open a browser and go to http://localhost:8080. We should see our application running.

This simple Go application is a good start for making a Docker image. We can learn more about building Docker images and how to manage them well in our work.

Writing a Dockerfile for Go

A Dockerfile is very important for making a Docker image for our Go application. It has a list of steps that Docker follows to build the image. Here is a simple guide to writing a Dockerfile for a Go application.

# Use the official Golang image as a base
FROM golang:1.20 AS builder

# Set the working directory inside the container
WORKDIR /app

# Copy the Go modules and download dependencies
COPY go.mod go.sum ./
RUN go mod download

# Copy the source code
COPY . .

# Build the Go application
RUN go build -o myapp .

# Use a minimal base image for the final image
FROM alpine:latest

# Set the working directory
WORKDIR /root/

# Copy the compiled binary from the builder stage
COPY --from=builder /app/myapp .

# Command to run the executable
CMD ["./myapp"]

Key Points:

  • Multi-stage builds: This Dockerfile uses multi-stage builds to keep image size smaller.
  • Dependencies: We install Go dependencies before copying the whole source code. This helps to make the build process faster.
  • Final Image: The final image uses Alpine to be smaller and lighter.

For more advanced setups, you can look at Docker - Setting NodeJS or Docker - Setting MySQL. Writing a good Dockerfile for Go helps our application work well in containers.

Building the Docker Image

Building a Docker image for our Go application is an important step in the Docker - Setting Go process. A Docker image is a small, independent package that has everything we need to run our application. To build a Docker image, we usually use the docker build command with a Dockerfile.

Here is a simple example of a Dockerfile for a Go application:

# Use the official Golang image as a base
FROM golang:1.18 AS builder

# Set the working directory inside the container
WORKDIR /app

# Copy the Go modules and download dependencies
COPY go.mod go.sum ./
RUN go mod download

# Copy the source code into the container
COPY . .

# Build the Go application
RUN go build -o myapp .

# Final stage
FROM alpine:latest

# Set the working directory in the final image
WORKDIR /root/

# Copy the built binary from the builder stage
COPY --from=builder /app/myapp .

# Command to run the binary
CMD ["./myapp"]

To build this Docker image, we go to our project folder and run this command:

docker build -t my-go-app .

This command will make a Docker image called my-go-app. We can see our images by using docker images. For more advanced ways to manage Docker images, we can check Docker Hub and Docker Registries. This step is very important in the Docker - Setting Go workflow. It gets our application ready for containerization.

Running the Go Application in a Container

To run our Go application in a Docker container, we first need to make sure we built our Docker image right. Once we have the image, we can follow these steps to start our Go application in a container.

  1. Run the Docker Container: We can use this command to run our Go application in a container. Just change your-go-image to the name of our built image:

    docker run -d -p 8080:8080 --name go-app your-go-image
    • -d means to run the container in detached mode.
    • -p 8080:8080 connects port 8080 of our host to port 8080 of the container.
    • --name go-app gives the container a name to help us manage it easier.
  2. Access the Application: We can open our web browser and go to http://localhost:8080 to see our running Go application.

  3. Check Running Containers: We can check if our Go application is running by listing all active containers with this command:

    docker ps
  4. Logs and Debugging: To see logs from our Go application, we can use:

    docker logs go-app

This simple process helps us run our Go application in a Docker container. For more complex setups, we can think about using other tools like Docker Compose to manage multi-container apps. If we want to learn about setting up databases like MySQL with our Go app, we can look at the right resources.

Managing Docker Containers

Managing Docker containers is very important for making sure our Go applications run well. Docker gives us commands to help with the life of containers. This includes creating them and removing them. Here are some key commands we can use:

  • Starting a container: We can use docker run to create and start a new container. For example:

    docker run -d --name my-go-app my-go-image
  • Stopping a container: If we want to stop a running container, we use:

    docker stop my-go-app
  • Removing a container: After stopping a container, we can remove it with:

    docker rm my-go-app
  • Listing containers: To see all running containers, we use:

    docker ps

    If we want to see all containers, including the stopped ones, we can use:

    docker ps -a
  • Viewing logs: To check the logs from a specific container, we can do:

    docker logs my-go-app
  • Accessing a container’s shell: If we need to debug, we might want to access a running Go application container:

    docker exec -it my-go-app /bin/sh

It is very important for us to understand these commands to manage our Docker containers well. If we want to learn more advanced ways to manage containers, we can look into Docker Compose for running multiple containers together.

Using Docker Compose for Go Projects

We can use Docker Compose to help us manage multi-container applications. This is especially useful when we are developing Go projects. Docker Compose lets us define and run these applications easily. We can set up multiple services in one docker-compose.yml file. This makes our development and deployment processes smoother.

To set up a Go project with Docker Compose, here are the steps we need to follow:

  1. Create a docker-compose.yml file: This file tells about our application’s services, networks, and volumes.

    version: "3"
    services:
      go-app:
        build: .
        ports:
          - "8080:8080"
        volumes:
          - .:/go/src/app
        environment:
          - ENV=development
  2. Define the service: Here, go-app is the main service. It builds from the current folder and connects local ports.

  3. Run Docker Compose: We need to run this command in our terminal to build and start our Go application:

    docker-compose up

Using Docker Compose makes our Go development easier. It also helps us connect with other services like databases or caches. If we want to learn more advanced options, we can check Docker Compose features. This tool is very important for effective Docker when we are setting up Go development.

Debugging Go Applications in Docker

We can debug Go applications in Docker using some tools and methods. Here is a simple way to make the debugging easier.

  1. Enable Debugging in Go: We need to use the dlv debugger. It works well with Go. First, we install Delve:

    go get github.com/go-delve/delve/cmd/dlv
  2. Modify Dockerfile: Next, we change our Dockerfile to add Delve and set the needed environment variables:

    FROM golang:1.18
    
    WORKDIR /app
    COPY . .
    
    RUN go install github.com/go-delve/delve/cmd/dlv@latest
    
    ENTRYPOINT ["dlv", "debug", "--headless", "--listen=:2345", "--api-version=2", "--accept-multiclient"]
  3. Run the Container: Now, we start our Docker container with this command:

    docker run --rm -p 2345:2345 my-go-app
  4. Connect to Delve: We can use a client like Visual Studio Code or just the command line to connect to the debugger:

    dlv connect localhost:2345
  5. Remote Debugging: Make sure our Go application runs with the --headless option. This lets us connect from another place.

Following these steps helps us debug Go applications in Docker better. For more tips on handling Docker containers, we can check our article on Docker - Working with Containers.

Docker - Setting Go - Full Example

We want to show how we can use Docker for a Go application. In this example, we will go through all the steps of Docker - Setting Go. We will create a simple Go application and run it inside a Docker container.

  1. Create a Simple Go Application:

    First, we create a file called main.go and add this content:

    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    func helloHandler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello, Docker - Setting Go!")
    }
    
    func main() {
        http.HandleFunc("/", helloHandler)
        http.ListenAndServe(":8080", nil)
    }
  2. Write a Dockerfile:

    Next, we need to create a Dockerfile in the same folder:

    # Use the official Golang image
    FROM golang:1.19
    
    # Set the working directory
    WORKDIR /app
    
    # Copy the Go application
    COPY . .
    
    # Build the Go application
    RUN go build -o myapp .
    
    # Expose the port
    EXPOSE 8080
    
    # Run the application
    CMD ["./myapp"]
  3. Build the Docker Image:

    To build the Docker image, we run this command in the terminal:

    docker build -t my-go-app .
  4. Run the Docker Container:

    Now we can run our Go application in a container with this command:

    docker run -p 8080:8080 my-go-app
  5. Access the Application:

    We can open our web browser and go to http://localhost:8080. We should see “Hello, Docker - Setting Go!”.

This example shows the full process of Docker - Setting Go. We wrote a Go application and put it in a container. If we want to learn more advanced setups, we can look at Docker Compose. It helps us to manage applications with many containers.

Conclusion

In this article on Docker - Setting Go, we looked at important steps. We talked about installing Docker, making a Go application, and writing a Dockerfile for Go. When we follow these steps, we can manage our Go applications in containers easily. This helps us with deployment and testing.

If we want more information, we can learn about Docker networking. We can also see how to set up Docker with Node.js. This will help us improve our development work.

Let’s use Docker - Setting Go to make our application development better.

Comments