search
HomeBackend DevelopmentGolangCustomize Go Builds on AWS SAM with Dockerfiles and Makefiles

Customize Go Builds on AWS SAM with Dockerfiles and Makefiles

This post continues the series Building APPS with AWS SAM and Go, building upon the first installment. The previous chapter highlighted AWS's limited guidance on structuring scalable Go projects without redundant code.

This article demonstrates techniques for managing build processes using Dockerfiles and Makefiles.

The accompanying code is available here: https://www.php.cn/link/5655cf23be4dda7082c8bb3a8d8f8016. Explore the different Git branches for various use cases.

Let's begin!

The Challenge

After developing a new project structure, I chose Nix for dependency management (languages, tools, libraries). Nix operates by creating a temporary shell with the specified dependencies.

I encountered an error when executing binaries built within a Nix shell:

<code>libc.so.6 not found in /nix/23fj39chsggb09s.libc</code>

This halted Lambda execution. Debugging revealed the root cause: Go sometimes dynamically links C libraries to executables, specifying system paths. The libraries linked to Nix-built executables were:

<code>$ ldd bootstrap 
        linux-vdso.so.1 (0x00007ffff7fc4000)
        libresolv.so.2 => /nix/store/65h17wjrrlsj2rj540igylrx7fqcd6vq-glibc-2.40-36/lib/libresolv.so.2 (0x00007ffff7fac000)
        libpthread.so.0 => /nix/store/65h17wjrrlsj2rj540igylrx7fqcd6vq-glibc-2.40-36/lib/libpthread.so.0 (0x00007ffff7fa7000)
        libc.so.6 => /nix/store/65h17wjrrlsj2rj540igylrx7fqcd6vq-glibc-2.40-36/lib/libc.so.6 (0x00007ffff7c00000)
        /nix/store/65h17wjrrlsj2rj540igylrx7fqcd6vq-glibc-2.40-36/lib/ld-linux-x86-64.so.2 => /nix/store/65h17wjrrlsj2rj540igylrx7fqcd6vq-glibc-2.40-36/lib64/ld-linux-x86-64.so.2 (0x00007ffff7fc6000)</code>

Nix's non-standard dependency storage, combined with Lambda's isolated Docker containers, prevented the Lambda from locating these libraries, as they only existed in my local Nix installation. A solution was needed to instruct AWS SAM on how to compile the code and manage library linking.

Deploying Go Projects to AWS

Two deployment methods exist:

Zip Files ?

Compile locally and send the executable to AWS in a .zip file. AWS copies the executable to the Docker container. This offers the fastest cold starts.

Docker Images ?

Provide AWS with instructions to compile within the execution Docker container. This ensures compatibility but results in slower cold starts.

Solutions

I opted for Dockerfiles to continue using Nix, but both methods are presented below.

Zip Files ?

For Zip files, use this project structure (note the Makefile):

<code>.
├── cmd/
│   ├── function1/
│   │   └── function1.go  # contains main()
│   └── function2/
│       └── function2.go  # contains main()
├── internal/
│   └── SHAREDFUNC.go
├── Makefile
├── go.mod
├── go.sum
├── samconfig.toml
└── template.yaml</code>

The Makefile defines build commands for each function using the build-<function_name></function_name> pattern (required by AWS SAM):

<code>.PHONY: build

build:
    sam build

build-HelloWorldFunction:
    GOARCH=amd64 GOOS=linux go build -tags lambda.norpc -o bootstrap ./cmd/function1/main.go
    cp ./bootstrap $(ARTIFACTS_DIR)

build-ByeWorldFunction:
    GOARCH=amd64 GOOS=linux go build -tags lambda.norpc -o bootstrap ./cmd/function2/main.go
    cp ./bootstrap $(ARTIFACTS_DIR)</code>

Inform SAM of this process:

<code>  HelloWorldFunction:
    Type: AWS::Serverless::Function 
    Metadata:
      BuildMethod: makefile
    Properties:
      CodeUri: ./
      Handler: bootstrap
      Runtime: provided.al2023
      Architectures:
        - x86_64
      Events:
        CatchAll:
          Type: Api 
          Properties:
            Path: /hello
            Method: GET</code>

BuildMethod: makefile tells SAM to use the Makefile, located where CodeUri specifies.

Docker Images ?

Create a Dockerfile and .dockerignore in the root directory:

<code>.
├── cmd/
│   ├── function1/
│   │   └── function1.go  # contains main()
│   └── function2/
│       └── function2.go  # contains main()
├── internal/
│   └── SHAREDFUNC.go
├── Dockerfile
├── .dockerignore
├── go.mod
├── go.sum
├── samconfig.toml
└── template.yaml</code>

The Dockerfile specifies build steps. ARG ENTRY_POINT specifies the lambda entry point at build time:

<code>FROM public.ecr.aws/docker/library/golang:1.19 as build-image
ARG ENTRY_POINT  # !IMPORTANT
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -tags lambda.norpc -o lambda-handler ${ENTRY_POINT}
FROM public.ecr.aws/lambda/provided:al2023
COPY --from=build-image /src/lambda-handler .
ENTRYPOINT ./lambda-handler</code>

Modify template.yaml:

<code>libc.so.6 not found in /nix/23fj39chsggb09s.libc</code>

Note Metadata and PackageType: Image. DockerBuildArgs passes ENTRY_POINT from the Dockerfile, allowing a single Dockerfile for all lambdas.

Conclusion

This detailed explanation provides a comprehensive approach to managing Go builds within AWS SAM using both Zip files and Docker images. The choice depends on the priorities of build speed versus deployment consistency.

The above is the detailed content of Customize Go Builds on AWS SAM with Dockerfiles and Makefiles. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Is Golang Faster Than C  ? Exploring the LimitsIs Golang Faster Than C ? Exploring the LimitsApr 20, 2025 am 12:19 AM

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang: From Web Services to System ProgrammingGolang: From Web Services to System ProgrammingApr 20, 2025 am 12:18 AM

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang vs. C  : Benchmarks and Real-World PerformanceGolang vs. C : Benchmarks and Real-World PerformanceApr 20, 2025 am 12:18 AM

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang vs. Python: A Comparative AnalysisGolang vs. Python: A Comparative AnalysisApr 20, 2025 am 12:17 AM

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools