如何在Heroku流水线中通过配置变量配置ReactiveMongo的mongodb.uri
Got it, let's walk through how to switch your Play Framework + ReactiveMongo setup from using application.prod.conf to Heroku config variables for your two-server upstream pipeline.
Step 1: Update Your application.conf to Use Environment Variables
First, modify your base application.conf file to pull the MongoDB URI from an environment variable instead of relying on application.prod.conf. Play's configuration system supports placeholder syntax for this:
# Replace your hardcoded or prod.conf-linked mongodb.uri with this mongodb.uri = ${?MONGODB_URI}
The ${?VAR_NAME} syntax tells Play: "If the environment variable VAR_NAME exists, use its value here; otherwise, fall back to any default you've set (or leave undefined if no default exists)."
Step 2: Set the Config Variable in Heroku
Now you need to define the MONGODB_URI variable in Heroku for each app in your pipeline. You have two easy ways to do this:
Option 1: Heroku Dashboard
- Go to your Heroku Pipeline dashboard
- Select each upstream server (app) in the pipeline
- Navigate to the Settings tab
- Under Config Vars, click Reveal Config Vars
- Add a new entry with:
- Key:
MONGODB_URI - Value: The full MongoDB URI you previously had in
application.prod.conf
- Key:
Option 2: Heroku CLI
Run this command for each app in your pipeline:
heroku config:set MONGODB_URI="mongodb+srv://your-user:your-password@cluster0.mongodb.net/your-db?retryWrites=true&w=majority" --app your-app-name
Replace the URI string with your actual MongoDB connection string, and your-app-name with the name of each upstream server in your pipeline.
Step 3: Verify the Configuration Works
To make sure everything is set up correctly:
- Check that the config variable exists for each app:
You should seeheroku config --app your-app-nameMONGODB_URIlisted with your value. - Optional: Add a quick log statement in your Play app to confirm the URI is being loaded properly. For example, in a startup module or controller:
Deploy this change, then check your app logs withimport play.api.Configuration import javax.inject.Inject class StartupService @Inject()(config: Configuration) { val mongoUri = config.get[String]("mongodb.uri") println(s"Loaded MongoDB URI from environment: $mongoUri") }heroku logs --tail --app your-app-nameto see the URI printed.
Bonus: Manage Pipeline-Specific Configs
Since you're using a Heroku pipeline, you can set different MONGODB_URI values for staging vs production environments (if needed). Just repeat Step 2 for each stage's app with the appropriate URI.
This approach keeps your configuration out of code, aligns with Heroku's best practices for pipelines, and eliminates the need for application.prod.conf in your multi-server setup.
内容的提问来源于stack exchange,提问作者Mark

