pass filePath to dockerfile as variable _ nodeJS dockerode Docker

684 Views Asked by At

In my case, I am creating a config.json that I need to copy from the host to my container.

I figured out there is some option that I can pass args to my dockerfile. so first step is :

1.create Dockerfile:

FROM golang
WORKDIR /go/src/app
COPY . .                     /* here we have /foo directory */
COPY  $CONFIG_PATH ./foo/
EXPOSE $PORT
CMD ["./foo/run", "-config", "./foo/config.json"]

as you can see, I have 2 variable [ "$CONFIG_PATH", "$PORT"].

so these to variables are dynamic and comes from my command in docker run. here I need to copy my config file from my host to my container, and I need to run my project with that config.json file.

after building image:

  1. second step:

get my config file from user and run the docker image with these variables.

let configFilePath = '/home/baazz/baaaf/config.json'
let port = "8080"
docker.run('my_image', null, process.stdout, { Env: [`$CONFIG_PATH=${configFilePath}`, `$PORT=${port}`] }).then(data => {

        }).catch(err => { console.log(err) })

I am getting this error message when I am trying to execute my code.

Error opening JSON configuration (./foo/config.json): open ./foo/config.json: no such file or directory . Terminating.

1

There are 1 best solutions below

2
On

You generally don’t want to COPY configuration files like this in your Docker image. You should be able to docker run the same image in multiple environments without modification.

Instead, you can use the docker run -v option to inject the correct config file when you run the image:

docker run -v $PWD/config-dev.json:/go/src/app/foo/config.json my_image

(The Dockerode home page shows an equivalent Binds option. In Docker Compose, this goes into the per-container volumes:. There’s no requirement that the two paths or file names match.)

Since file paths like this become part of the external interface to how people run your container, you generally don’t want to make them configurable at build time. Pick a fixed path and document that that’s the place to mount your custom config file.