Home > Net >  How to download golang and node in docker container
How to download golang and node in docker container

Time:12-10

I am building a simple node server to run in docker. I have introduced a small golang module that can be executed by running

go run /root/component-review-handler/downloader/main.go -build 1621568 -outdir /usr

I am currently running this locally in my node server by running the follow script on startup

exec(
    `cd ${process.env.ROOT_PATH}/component-review-handler && go run cmd/downloader/main.go`,
    (error, stdout, stderr) => {
      if (error) {
        logger.error(`error: ${error.message}`)
        return
      }
      if (stderr) {
        logger.log(`stderr: ${stderr}`)
        return
      }
      logger.log(`stdout: ${stdout}`)
    }
  )

But When I run the code in docker, I get the following error

error: Command failed: cd /usr/src/app/component-review-handler && go run cmd/downloader/main.go

/bin/sh: 1: go: not found

Does anyone know how I can install both node and golang in my docker container? Current Dockerfile

FROM node:14

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

ENV NODE_TLS_REJECT_UNAUTHORIZED='0'

EXPOSE 3000

CMD ["node", "server.js" ]

CodePudding user response:

Go is a compiled language, and you shouldn't usually need the Go toolchain just to run a Go program.

I'd use a multi-stage build for this. The first stage is FROM golang to have the toolchain and build the binary; the second COPY --from the first image into a directory that's normally on the search path.

FROM golang:1.17 AS downloader
WORKDIR /app                       # not under /go
COPY component-review-handler/ ./  # (double-check this COPY syntax)
RUN go build -o downloader ./cmd/downloader

FROM node:14
# vvv add this line
COPY --from=downloader /app/downloader /usr/local/bin/

# same as before
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
ENV NODE_TLS_REJECT_UNAUTHORIZED='0'
EXPOSE 3000
CMD ["node", "server.js"]

Since the binary is now in /usr/local/bin which is a default $PATH directory, in your code you can just run it, without the cd or go run parts

const { execFile } = require('child_process');
execFile('downloader',
         (error, stdout, stderr) => { ... });
  • Related