search
HomeBackend DevelopmentGolangGolang chromedp dockerfile

Golang chromedp dockerfile

In modern software development, Docker has become an indispensable tool that helps developers quickly build, deploy and manage applications. As an efficient and concise programming language, Golang is also favored by developers. So, how to develop applications using Golang in Docker? This article will introduce how to write a Dockerfile for a Golang application and use the chromedp library to implement automated web testing. If you are interested in Golang, Docker and Web automated testing, you may wish to continue reading.

Question content

I have a golang code that uses chromedp to connect to the user's local chrome This is my code:

package main

import (
    "context"
    "fmt"
    "log"
    "os"
    "time"

    "github.com/chromedp/chromedp"
    "github.com/gin-gonic/gin"
)

func main() {
    api := gin.default()

    api.get("api/jwt", func(c *gin.context) {
        opts := append(chromedp.defaultexecallocatoroptions[:],
            chromedp.flag("headless", false),
            chromedp.flag("disable-gpu", true),
            chromedp.flag("no-sandbox", true),
            chromedp.flag("disable-dev-shm-usage", true),
            chromedp.flag("disable-browser-side-navigation", true),
            chromedp.flag("disable-infobars", true),
            chromedp.flag("disable-extensions", true),
            chromedp.flag("disable-notifications", true),
            chromedp.flag("disable-default-apps", true),
            chromedp.flag("disable-background-timer-throttling", true),
            chromedp.flag("disable-backgrounding-occluded-windows", true),
            chromedp.flag("disable-renderer-backgrounding", true),
        )

        allocctx, cancel := chromedp.newexecallocator(context.background(), opts...)
        defer cancel()

        ctx, cancel := chromedp.newcontext(allocctx)
        defer cancel()

        var localstoragedata string // declaração da variável localstoragedata

        err := chromedp.run(ctx,
            chromedp.navigate("https://csonlinetenant.b2clogin.com/csonlinetenant.onmicrosoft.com/oauth2/v2.0/authorize"),
            chromedp.sleep(5*time.second),
            chromedp.waitvisible(`#fgh`),
            chromedp.sendkeys(`#fghfg`, "fghfgh"),
            chromedp.sendkeys(`#xcvxcv`, "xcxcvcxv"),
            chromedp.click(`#thgh`, chromedp.byid),
            chromedp.sleep(5*time.second),
            chromedp.click(`dfgd`, chromedp.byid),
            chromedp.sleep(15*time.second),
            chromedp.evaluateasdevtools(`localstorage.getitem('c')`, &localstoragedata),
        )
        if err != nil {
            log.printf("error: %v", err)
            return
        }

        fmt.println("bearer", localstoragedata)

        // restante do código...

        c.json(200, gin.h{
            "success": localstoragedata,
        })
    })

    listenaddr := os.getenv("listen")

    if val, ok := os.lookupenv("functions_customhandler_port"); ok {
        listenaddr = ":" + val
    }
    if listenaddr == "" {
        listenaddr = ":8080"
    }

    api.run(listenaddr)
}

So I made a dockerfile with what my client needs to use this application (I installed chrome and built my golang in the image)

docker file:

from golang:1.20 as build-stage

workdir /app

# instale as dependências do chrome
run wget -q -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list
run apt-get update && apt-get -y install google-chrome-stable
run chrome &


copy go.mod go.sum ./
run go mod download

copy *.go ./

run cgo_enabled=0 goos=linux go build -o /dockergo

# run the tests in the container
from build-stage as run-test-stage
run go test -v ./...

# deploy the application binary into a lean image
from gcr.io/distroless/base-debian11 as build-release-stage

workdir /

copy --from=build-stage /dockergo /dockergo

expose 8080

user nonroot:nonroot

entrypoint ["/dockergo"]

Image built successfully and without headaches But when testing the docker image locally I get this error:

Error: exec: "google-chrome": executable file not found in $PATH

What does this error mean? My chrome is not running? How can I run it?

Solution

Chrome browser is only installed in build-stage. It is not available in the final image created by build-release-stage.

I try to install chrome using this dockerfile:

# deploy the application binary into a lean image
from gcr.io/distroless/base-debian11 as build-release-stage

run wget -q -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list
run apt-get update && apt-get -y install google-chrome-stable
run chrome &

but fails with the following message:

...
step 2/4 : run wget -q -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -     && echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list
 ---> running in 7596202a5684
failed to create shim task: oci runtime create failed: runc create failed: unable to start container process: exec: "/bin/sh": stat /bin/sh: no such file or directory: unknown

I think you have to choose another base image where you can easily install chrome. A better option is to use chromedp/headless-shell as the base image. This image contains chrome's headless shell, which is very small. The demo dockerfile below also shows first compiling the test binary and then running the tests in the chromedp/headless-shell image:

FROM golang:1.20.5-buster AS build-stage

WORKDIR /app

COPY go.mod go.sum ./
RUN go mod download

COPY . .

RUN CGO_ENABLED=0 go build -o dockergo
# Build the test binary
RUN CGO_ENABLED=0 go test -c -o dockergo.test

# Run the tests in the container
FROM chromedp/headless-shell:114.0.5735.199 AS run-test-stage

WORKDIR /app
# Copy other files that is needed to run the test (testdata?).
COPY . .
COPY --from=build-stage /app/dockergo.test ./dockergo.test
RUN /app/dockergo.test -test.v

# Deploy the application binary into a lean image
FROM chromedp/headless-shell:114.0.5735.199 AS build-release-stage

COPY --from=build-stage /app/dockergo /dockergo

EXPOSE 8080

ENTRYPOINT ["/dockergo"]

The above is the detailed content of Golang chromedp dockerfile. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
String Manipulation in Go: Mastering the 'strings' PackageString Manipulation in Go: Mastering the 'strings' PackageMay 14, 2025 am 12:19 AM

Mastering the strings package in Go language can improve text processing capabilities and development efficiency. 1) Use the Contains function to check substrings, 2) Use the Index function to find the substring position, 3) Join function efficiently splice string slices, 4) Replace function to replace substrings. Be careful to avoid common errors, such as not checking for empty strings and large string operation performance issues.

Go 'strings' package tips and tricksGo 'strings' package tips and tricksMay 14, 2025 am 12:18 AM

You should care about the strings package in Go because it simplifies string manipulation and makes the code clearer and more efficient. 1) Use strings.Join to efficiently splice strings; 2) Use strings.Fields to divide strings by blank characters; 3) Find substring positions through strings.Index and strings.LastIndex; 4) Use strings.ReplaceAll to replace strings; 5) Use strings.Builder to efficiently splice strings; 6) Always verify input to avoid unexpected results.

'strings' Package in Go: Your Go-To for String Operations'strings' Package in Go: Your Go-To for String OperationsMay 14, 2025 am 12:17 AM

ThestringspackageinGoisessentialforefficientstringmanipulation.1)Itofferssimpleyetpowerfulfunctionsfortaskslikecheckingsubstringsandjoiningstrings.2)IthandlesUnicodewell,withfunctionslikestrings.Fieldsforwhitespace-separatedvalues.3)Forperformance,st

Go bytes package vs strings package: Which should I use?Go bytes package vs strings package: Which should I use?May 14, 2025 am 12:12 AM

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

How to use the 'strings' package to manipulate strings in Go step by stepHow to use the 'strings' package to manipulate strings in Go step by stepMay 13, 2025 am 12:12 AM

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Go strings package: how to improve my code?Go strings package: how to improve my code?May 13, 2025 am 12:10 AM

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

What are the most useful functions in the GO bytes package?What are the most useful functions in the GO bytes package?May 13, 2025 am 12:09 AM

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Mastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMay 13, 2025 am 12:07 AM

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

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 Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.