Thank you life888888 for such a detailed answer above, taking inspiration from it, I did something simpler for my use case to make it work. Instead of trying to create the binary in Dockerfile itself, I simply used the Dockerfile to create the environment I wanted matching the one I had on the host. This is defined in the BASE_IMAGE
argument where it pull the image I needed (which had the right OS for linux and go installed). So this is simply how my Dockerfile looked:
FROM ${BASE_IMAGE}:${BASE_TAG} as base
WORKDIR /workspace
COPY go.mod go.mod
COPY go.sum go.sum
ADD . go_mylib
RUN go mod download
Then I build the container on my M1 Mac using the command:
$ docker build -t go_mylib:v1 --platform linux/amd64 .
Run the image using:
$ docker run -i -t --sysctl net.ipv6.conf.all.disable_ipv6=0 --platform linux/amd64 --name go_mylib-v1 go_mylib:v1 /bin/bash
Once inside the container's bash, I go into the project folder and then run the command to create a shared library:
# cd go_mylib/
# go build -o libmybinary.so -buildmode=c-shared main.go
And finally exiting the container, I copy the binary generated to my local folder using this command:
$ docker cp go_mylib-v1:/workspace/go_mylib/libmybinary.so .
(where /workspace/go_mylib/libmybinary.so
is the path of the file inside my container and .
refers to the current folder in my local system.
I finally load this library from my Java code by using:
MyLib INSTANCE = Native.load("mybinary", MyLib.class);
and it works on the host as expected.