Initialize the Postgres Database#
Working with a remote database can be a challenge. The Postgres database you created in your Kubernetes cluster needs to be initilized with Django’s data (i.e. you have to run python manage.py migrate
) before Django can use it. But the service doesn’t allow for external communication. In this lab you’ll use a the kubectl port-forward
command to enable access from your dev box.
Create a Port Forward#
The kubectl port-forward
command creates a secure connection from the machine you run the command on (your dev box) to the inside of your Kubernetes cluster. The port-forward
command can forward connections to a Service
or directly to a Pod
. Using a forwarded port you will be able to access your database for debugging and setup purposes.
Start by creating a port forward:
$ kubectl port-forward service/postgres 5432:5432
Note
The kubectl
command keeps running as long as the port is forwarded. Subsequent commands should be run in another terminal.
Connect Using psql
#
With the port forward running you can connect using the psql
command.
$ psql -h localhost -p 5432 -U postgres
Note
The password should be django
If the port forward is working you should see the Postgres command prompt.
Run Django’s Migrations#
The database needs to be initialized before Django can use it. If you were able to connect in the last step then you should be able to run the migration from your dev box. Set up the environment variables to match the port forward and run the following:
$ export SECRET_KEY=blahblah
$ export DB_NAME=mysite
$ export DB_USER=postgres
$ export DB_PASSWORD=django
$ export DB_HOST=localhost
$ python3 ./manage.py migrate
$ python3 ./manage.py createsuperuser
With the management tasks complete you should be able to update the Django pod definition to use the newly created Postgres database.
Stop the Port Forward#
With the management tasks complete you can stop the port-forward
command with Ctrl-C