Shiphp The PHP Developer's Guide

Running a PHP Application with Postgres and Docker

MySQL may be the standard choice in relational databases for PHP developers, but Postgres is a great option as well. The setup is very similar, and running Postgres and PHP within Docker containers is just as easy.

1. Create a PHP Script that Connects to Postgres

Let’s start by writing a simple PHP script that will connect to a Postgresql database. All the script is going to do is connect and let us know that the connection was successful:

index.php

<?php

// Connect to the database
$dbconn = pg_connect("host=database dbname=admin user=admin password=4LyM7F39w97n");
// Show the client and server versions
print_r(pg_version($dbconn));

This file connects to a Postgres database using pg_connect and then shows the database’s version number in the terminal. This isn’t a very useful real-world script, but it’s a great way to test our Docker setup.

2. Start the Postgres Container

Next, we want to start up a Postgres Container. In this case, we’re using version 9.6 from Postgres’ official Docker image:

docker run -d --rm --name database -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=4LyM7F39w97n postgres:9.6

What’s going on here?

3. Run the PHP Script within a Container

When we run the PHP script we want to make sure it connects to the Postgres container and that it has all the required Postgresql extensions. Since I’ve been using Postgres quite a bit lately, I’ve created a Docker image for just such an occasion, but feel free to create your own if you’d prefer.

The command I ended up with is:

docker run --rm -v $(pwd):/app -w /app --link database karllhughes/php-cli-postgres php index.php

What’s going on here?

If everything worked properly, you should see an array with all the database version info:

Array
(
    [client] => 9.4.12
    [protocol] => 3
    [server] => 9.6.3
    [server_encoding] => UTF8
    [client_encoding] => UTF8
    [is_superuser] => on
    [session_authorization] => admin
    [DateStyle] => ISO, MDY
    [IntervalStyle] => postgres
    [TimeZone] => UTC
    [integer_datetimes] => on
    [standard_conforming_strings] => on
    [application_name] => 
)

You’ve now connected a PHP command line script with a Postgres database container. There’s a lot of work left if you want to make this a useful application, but the rest is just code.

Like this Post?

Learn to build your first Dockerized PHP application.

In this book, PHP developers will learn everything they need to know to start building their applications on Docker, including:

  • Installing dependencies using Composer.
  • Getting data from a third-party API.
  • Saving data to a MySQL database.
  • Using a web framework (SlimPHP) for routing.
  • Storing environmental variables securely.
  • And much more!

You can buy this book on Leanpub today.

Buy it Now!