Hi, I’ve included the following code in my dockerfile to set the the DATABASE_URL env variable in a NextJS project, I am using the echo command to log the DATABASE_URL_SECRET variable first to check that it has been correctly added:
# Set DATABASE_URL_SECRET
RUN --mount=type=secret,id=DATABASE_URL_SECRET \
DATABASE_URL_SECRET="$(cat /run/secrets/DATABASE_URL_SECRET)" \ && echo "DATABASE_URL_SECRET: $DATABASE_URL_SECRET"
# Set DATABASE_URL from DATABASE_URL_SECRET
ENV DATABASE_URL=$DATABASE_URL_SECRET
Disregard my previous comment. There is a syntax error in the above. At a minimum, remove the &&. Either remove the \ or have it be the last character on the line.
Got it, would you recommend the secrets approach over something like this?
# Define a build argument for DATABASE_URL with a default value
ARG DATABASE_URL=""
# Set the DATABASE_URL environment variable using the build argument
ENV DATABASE_URL=${DATABASE_URL}
then in the command line call fly deploy --build-arg DATABASE_URL=DB_URL
If you take care to put that in a throw-away build stage that would be fine, I would just make sure that the secret isn’t captured in the image itself which would increase the change of it leaking.
# Set DATABASE_URL_SECRET
RUN --mount=type=secret,id=DATABASE_URL_SECRET \
DATABASE_URL_SECRET="$(cat /run/secrets/DATABASE_URL_SECRET)" \
echo "DATABASE_URL_SECRET: $DATABASE_URL_SECRET"
# Set DATABASE_URL from DATABASE_URL_SECRET
ENV DATABASE_URL=$DATABASE_URL_SECRET
--mount=type=secret will only set the secret for that one RUN statement. Find the place in your Dockerfile where you need access to this secret, and replace the word RUN with the first two lines of the above.
Thanks. I passed the secret as DATABASE_URL in front of the npm run build line and now the deploy works.
# Set DATABASE_URL
RUN --mount=type=secret,id=DATABASE_URL \
DATABASE_URL="$(cat /run/secrets/DATABASE_URL)" \
npm run build
Do I need to add the secret in the command line call every time I deploy to fly:
fly deploy \
--build-secret DATABASE_URL=DB_URL
Or is there a way to automatically do this whenever a deploy is triggered? I have the DB_URL in a .env file but was getting errors when I tried reading the value in a package.jsonscript I define like npm run deploy.
Ah! Now finally the post I said to disregard applies:
You should be able to write a script that reads the .env file; or you can have npm run deploy use fly console with the Dockerfile that you see on the above page.
Create fly-deploy.sh file in root directory with the following contents:
#!/bin/bash
# Load environment variables from the .env.local file
source .env.local
# Run the fly deploy command with the loaded environment variable
fly deploy --build-secret DATABASE_URL="$DATABASE_URL"
In command line run chmod +x fly-deploy.sh
so that .sh file has execute permissions
Add "deploy": "./fly-deploy.sh", to package.json "scripts"
so that calling npm run deploy deploys to fly.