Table of Contents
Question content
Solution
Home Backend Development Golang Golang chromedp dockerfile

Golang chromedp dockerfile

Feb 09, 2024 am 10:09 AM
golang development

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)
}
Copy after login

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"]
Copy after login

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
Copy after login

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 &
Copy after login

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
Copy after login

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"]
Copy after login

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

Statement of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1270
29
C# Tutorial
1250
24
Develop powerful desktop applications with Golang Develop powerful desktop applications with Golang Mar 19, 2024 pm 05:45 PM

Use Golang to develop powerful desktop applications. With the continuous development of the Internet, people have become inseparable from various types of desktop applications. For developers, it is crucial to use efficient programming languages ​​to develop powerful desktop applications. This article will introduce how to use Golang (Go language) to develop powerful desktop applications and provide some specific code examples. Golang is an open source programming language developed by Google. It has the characteristics of simplicity, efficiency, strong concurrency, etc., and is very suitable for

Security challenges in Golang development: How to avoid being exploited for virus creation? Security challenges in Golang development: How to avoid being exploited for virus creation? Mar 19, 2024 pm 12:39 PM

Security challenges in Golang development: How to avoid being exploited for virus creation? With the wide application of Golang in the field of programming, more and more developers choose to use Golang to develop various types of applications. However, like other programming languages, there are security challenges in Golang development. In particular, Golang's power and flexibility also make it a potential virus creation tool. This article will delve into security issues in Golang development and provide some methods to avoid G

Steps and tips for programming with Golang on Mac Steps and tips for programming with Golang on Mac Mar 03, 2024 am 08:30 AM

Title: Steps and techniques for using Golang programming on Mac In the current field of software development, Golang (also known as Go), as an efficient, concise, and highly concurrency programming language, has attracted the attention of more and more developers. use. When programming Golang on the Mac platform, you can use some tools and techniques to improve development efficiency. This article will introduce the steps and techniques of using Golang programming on Mac, and provide specific code examples to help readers better understand and apply. Step 1: Install Gol

Research on the impact and role of Golang on the development of blockchain Research on the impact and role of Golang on the development of blockchain Feb 26, 2024 pm 04:24 PM

Golang (Go language for short) as a programming language has gradually emerged in the blockchain field in recent years. Its efficient concurrent processing capabilities and concise syntax features make it a favored choice in blockchain development. This article will explore how Golang helps the development of blockchain and demonstrate its superiority in blockchain applications through specific code examples. 1. Golang’s advantages in the blockchain field: Efficient concurrent processing capabilities: Nodes in the blockchain system need to process a large amount of transactions and data at the same time, and Gola

What programming languages ​​are commonly used by Golang developers? What programming languages ​​are commonly used by Golang developers? Mar 18, 2024 pm 09:06 PM

Golang is an open source programming language developed by Google and is widely used in back-end service development, cloud computing, network programming and other fields. As a statically typed language, Golang has an efficient concurrency model and a powerful standard library, so it is favored by developers. However, in actual development, Golang developers usually need to combine other programming languages ​​for project development to meet the needs of different scenarios. PythonPython is an object-oriented programming language that is concise, clear, and easy to learn.

Go kit framework helps improve Golang API performance Go kit framework helps improve Golang API performance May 07, 2024 pm 03:24 PM

Gokit is a Golang microservice framework that improves API performance through optimized, scalable, maintainable and test-friendly features. It provides a range of tools and patterns that enable users to quickly build performant and maintainable APIs. In actual production, it is widely used in API construction of large platforms such as Netflix, Spotify and Uber, handling massive requests.

A deep dive into Golang errors: cause analysis and resolution strategies A deep dive into Golang errors: cause analysis and resolution strategies Mar 20, 2024 am 09:21 AM

As a fast and efficient programming language, Golang language is favored by more and more developers. However, in daily development, we will inevitably encounter various errors. How to correctly analyze the causes of errors and find solution strategies is an important skill that every Golang developer needs to understand and master in depth. Error analysis type assertion failure In Golang, type assertion is a common operation, but sometimes if the types do not match, panic will occur. Here is a simple example: varxinter

Sharing of practical techniques for replacing spaces in Golang Sharing of practical techniques for replacing spaces in Golang Mar 13, 2024 am 09:15 AM

Title: Sharing practical techniques for replacing spaces in Golang. With the popularity and development of the Internet, program design and development have become more and more important. In the programming process, data processing is a very critical part. When processing text data, you often encounter situations where you need to replace spaces. This article will share how to implement the technology of replacing spaces in Golang and provide specific code examples. Why do I need to replace spaces? Spaces are one of the common special characters in text data. Sometimes we need to replace spaces with other characters or remove spaces.

See all articles