Deploying a Simple GoLang Project with Multistage Build Dockerfile

Go calculator with an interactive command-line interface and optimize its Docker image size using multistage builds.

Deploying a Simple GoLang Project with Multistage Build Dockerfile

Before getting started, ensure you have the following prerequisites:

  • Docker installed and properly configured.

Overview of Project:

calculator-golang-multistage-docker/
│
├── calculator.go
└── Dockerfile

Building a Simple Calculator in Go: Interactive Command-Line Interface

calculator.go

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    fmt.Println("Calculator app using golang")

    for {
        // Read input from the user
        reader := bufio.NewReader(os.Stdin)
        fmt.Print("Enter any calculation (Example: 1 + 2 (or) 2 * 5 -> Please maintain spaces as shown in example): ")
        text, _ := reader.ReadString('\n')

        // Trim the newline character from the input
        text = strings.TrimSpace(text)

        // Check if the user entered "exit" to quit the program
        if text == "exit" {
            break
        }

        // Split the input into two parts: the left operand and the right operand
        parts := strings.Split(text, " ")
        if len(parts) != 3 {
            fmt.Println("Invalid input. Try again.")
            continue
        }

        // Convert the operands to integers
        left, err := strconv.Atoi(parts[0])
        if err != nil {
            fmt.Println("Invalid input. Try again.")
            continue
        }
        right, err := strconv.Atoi(parts[2])
        if err != nil {
            fmt.Println("Invalid input. Try again.")
            continue
        }

        // Perform the calculation based on the operator
        var result int
        switch parts[1] {
        case "+":
            result = left + right
        case "-":
            result = left - right
        case "*":
            result = left * right
        case "/":
            result = left / right
        default:
            fmt.Println("Invalid operator. Try again.")
            continue
        }

        // Print the result
        fmt.Printf("Result: %d\n", result)
    }
}

Creating the Multistage Build Dockerfile:

FROM ubuntu AS build

RUN apt-get update && apt-get install -y golang-go

ENV GO111MODULE=off

COPY . .

RUN CGO_ENABLED=0 go build -o /app .

FROM scratch

# Copy the compiled binary from the build stage
COPY --from=build /app /app

# Set the entrypoint for the container to run the binary
ENTRYPOINT ["/app"]

Building and Running the Docker Image:

  • Building the Image: Open a terminal, navigate to the project directory, and execute the following command to build the Docker image:

      docker build -t calculator-multistage .
    
  • Running the Container: Once the image is built, run the Docker container using the following command:

      docker run -it --rm calculator-multistage
    

Contributing:

Contributions are welcome! If you find any issues or want to improve this project, please open an issue or submit a pull request.

GitHub Link of project

Note: In the GitHub link, there is another folder named "without" containing a Docker file that is not multistage. You can also run that and see the difference in the size of the images.

Happy Learning ^_^

Did you find this article valuable?

Support Devops Related Articles by becoming a sponsor. Any amount is appreciated!