Search code examples
pythondockercgo

Building Docker container that calls CGO from python


My main app is python, and I have some Go code that I want to call from python inside the Docker container. Usually I have compiled the Go code using CGO with go build -buildmode=c-shared -o dllname.dll, and used that from other languages. In python I can run the dll using the ctypes module and cdll.LoadLibrary (on windows).

In my mind, this is how it would work in a Dockerfile (I am new to Docker):

  1. Install Go
  2. Install Go dependencies/libraries
  3. Install a suitable C compiler
  4. Copy the Go/Cgo source files into the container
  5. Compile the Go/Cgo code into a shared binary using CGO_ENABLED=1 go build -buildmode=c-shared
  6. Copy python source files into container
  7. Assign python entry point with CMD

I have made many futile attempts at making such a Dockerfile. Is this doable?


Solution

  • Got it to work using the golang:1.17.2-bullseye image as suggested by jakub. This is the Dockerfile:

    FROM golang:1.17.2-bullseye as builder
    WORKDIR /go/src/app
    COPY ./lib/cgo .
    RUN go get ./...
    RUN CGO_ENABLED=1 go build -buildmode=c-shared -o cgolibname.so .
    
    FROM python:3.9
    WORKDIR /app
    COPY ./appname .
    COPY --from=builder /go/src/app/cgolibname.so .
    CMD [ "python", "main.py" ]