Introduction
When deploying a Kong API Gateway alongside a PostgreSQL database in Docker, it’s crucial to ensure that the database is fully initialized before executing any migrations. This article outlines how to create a custom Kong image with PostgreSQL client utilities and implement checks to confirm the database's readiness.
Custom Kong Image with PostgreSQL Client
To check the status of your PostgreSQL instance from the Kong container, you can build a custom Docker image that includes the PostgreSQL client tools. Here’s how to do it:
# Use the official Kong image as the base
FROM kong:latest
# Install PostgreSQL client utilities
RUN yum install postgresql -y && yum clean all
This Dockerfile installs the necessary PostgreSQL client tools, allowing you to use commands like psql and pg_isready.
Verifying PostgreSQL Readiness
Using psql
You can use the psql command to check if the PostgreSQL server is ready. Here’s an example command:
psql -h postgres -U polling -w -c '\l'
However, if you encounter the error psql: fe_sendauth: no password supplied, it may be due to the user not having a password set. To resolve this, ensure that the user polling is configured correctly in PostgreSQL, or consider adding a password for this user.
Using pg_isready
The pg_isready utility is another option for checking PostgreSQL readiness. However, it may not be included in the default PostgreSQL package installed in your custom image. If you need this utility, you might have to install a more comprehensive PostgreSQL package or find an alternative way to check readiness without installing the full server.
Best Practices for Startup Order
To avoid race conditions where Kong attempts to start before PostgreSQL is ready, consider implementing a wait script or using Docker Compose health checks. Here’s a simple example of a wait script:
#!/bin/bash
# Wait for PostgreSQL to be ready
until pg_isready -h postgres -U polling; do
echo "Waiting for PostgreSQL..."
sleep 2
done
# Run migrations after PostgreSQL is ready
kong migrations bootstrap
This script will continuously check if PostgreSQL is ready before proceeding with the migrations, ensuring a smooth startup process.
Conclusion
By creating a custom Kong image with PostgreSQL client tools and implementing readiness checks, you can effectively manage the startup order of your services. This approach helps prevent migration failures and ensures that your application runs smoothly.