I have an docker-compose.yml file which passes secrets via files:
compose.yml
services:
node-example:
container_name: distroless-getsecret
ports:
- "80:80"
secrets:
- THEPASSWORD1
- THEPASSWORD2
build:
context: .
image: "distroless-getsecret:1"
secrets:
THEPASSWORD1:
file: ./.secrets/THEPASSWORD1
THEPASSWORD2:
file: ./.secrets/THEPASSWORD2
Dockerfile
FROM node:20
WORKDIR /usr/src/app
COPY node-files .
RUN npm ci && npm run build
ENV NODE_ENV=production
CMD ["node", "dist/node-server.js"]
folder directory
/compose.yml
Dockerfile
.secrets/
PASSWORD1
PASSWORD2
node-files/
src/
get-secrets.ts
node-server.ts
package.json
package-lock.json
tsconfig.json
.dockerignore
node-files/get-secret.ts
import fs from "fs";
type SecretsArray = string[];
interface SecretsObj {
[key: string]: string;
}
export const getSecrets = (
arr: SecretsArray
) => {
const secretPath = "/run/secrets/";
const parsed: SecretsObj = {};
arr.forEach((item) => {
try {
console.log(`try to get file = ${secretPath}${item}`);
parsed[item] = fs.readFileSync(`${secretPath}${item}`, {
encoding: "utf8",
});
} catch (err: any) {
if (err.code !== "ENOENT") {
console.error(`There was a problem getting secret: ${item}`, err);
}
}
});
return parsed;
};
const env = getSecrets(['THEPASSWORD1', 'THEPASSWORD2'])
console.log('NODE_ENV =', process.env.NODE_ENV);
console.log('process.env.THEPASSWORD1=', process.env.THEPASSWORD1); // expect undefined
console.log("parsed THEPASSWORD1=", env.THEPASSWORD1); // expect value
When running following command:
docker-compose up
I will get a node server running and it will log the output of the THEPASSWORD1 to show it loads it from /run/secrets/THEPASSWORD1
I need to also be able to do this with docker run command.
It seems there is no way to do this unless I bind mount a volume to /run/secrets. Only doing that won’t work either because the path /run/secrets is protected and it won’t bind mount to it. When doing docker exec -it mycontainer sh > and cd of that location, /run folder does not container the secrets folder.
It would be nice to have a solution for this. It seems odd to have docker-compose able to do it but not docker run.
See repo example I created with the problem:
https://github.com/inspiraller/docker-node-get-secrets/tree/feature/run-volume-example