Connect App to Database#
We’ve seen that we can use psql from our EC2 instance to connect to the Postgres DB running in RDS. That’s no small feat; a bunch of things had to be configured just right for it to work.
The good news is that it will take only one more small step to get the PatientPing app communicating with the database automatically. Instead of using psql manually, we’ll set a DATABASE_URL environment variable that the Python app can read when it starts up!
Assignment#
The PatientPing app still can’t connect to the Postgres database! Fix the problem by adding a .env file with DB connection info on the EC2 instance.
- SSH into the EC2 instance and navigate to the app directory:
ssh patientping
cd ~/patientping-webTo keep things simple, make sure the app isn’t running at this point.
- In that directory, use a terminal text editor (e.g.
nanoorvim) to open a new.envfile:
nano .env- Enter a
DATABASE_URLenvironment variable in the following format, with your actual values:
DATABASE_URL='postgresql://postgres:PASSWORD@patientping-db.RANDOM-ID.us-east-1.rds.amazonaws.com:5432/patientping'- Save and exit the
.envfile (Ctrl+X, Y, Enter innano; good luck invim). - Confirm that the
.envfile looks correct, and that you’re in the right directory:
pwd # /home/ec2-user/patientping-web
cat .env # DATABASE_URL='postgresql://postgres:PASSWORD...'- Start the server:
uv run patientping.py- Confirm that things are working properly:
- If the app was able to connect to the database on startup, you should see a
DB init okmessage in the terminal. - You should also see PatientPing appointment reminders being generated and inserted into the DB every ~5 seconds.
- Open a browser on your local machine and visit
http://YOUR.EC2.INSTANCE.IP:8080. The app should load; status should be green withDB connectedandInternet egress OK; and you should see a list of reminders (refresh the page to see new ones).
- If the app was able to connect to the database on startup, you should see a