How to change the default port in PostgreSQL

PostgreSQL, by default, listens on port 5432. There might be scenarios where you need to change this default port due to conflicts, security concerns, or other reasons. This guide walks you through the steps to do this efficiently and safely.

Prerequisites

Ensure you have the following:

  • Administrative or superuser access to the PostgreSQL server
  • Familiarity with command-line tools
  • Before making changes to your database system, always take a backup

Locate the configuration file

The PostgreSQL configuration file, typically named postgresql.conf, contains various settings including the port number. It's located in the PostgreSQL data directory. The location might vary based on the installation method and OS.

For standard installations on Unix-like systems, the configuration file can often be found in:

/etc/postgresql/{VERSION}/main/postgresql.conf or /var/lib/pgsql/{VERSION}/data/postgresql.conf

On Windows installations, it's usually in:

C:\Program Files\PostgreSQL\{VERSION}\data\postgresql.conf

Modify the port number

Open postgresql.conf in your preferred text editor. For instance, using nano:

nano /path/to/your/postgresql.conf

Search for the port setting, which might look like:

# port = 5432

Uncomment the line (remove the # at the start) and change 5432 to your desired port number. For example, to set the port to 5433:

port = 5433

Save and close the file.

Restart the PostgreSQL service

The change will only take effect after a service restart.

On Unix-like systems:

sudo systemctl restart postgresql

On Windows, restart using the Services application or run:

pg_ctl restart -D "C:\Program Files\PostgreSQL\{VERSION}\data"

Verify the port change

Use the netstat tool or ss command to verify PostgreSQL is now listening on the new port.

netstat -tuln | grep [new_port_number]

or

ss -tln | grep [new_port_number]

You should see your PostgreSQL instance listening on the specified port.

Update client connections

Once you’ve updated your PostgreSQL database port, you’ll have to ensure that any applications or clients connecting to the PostgreSQL server are updated to use the new port. This often involves updating connection strings or configurations in those applications. Ideally, you should compile a list of all services that connect to your database before changing the port so that you can update them all as soon as the port has changed.

If you’re using a cloud-based tool like Basedash to access your database, you’ll only need to update the connection to your database once for your whole team. This might make the migration much smoother, especially if you have multiple developers or non-technical teammates who need to access your database.

Invite only

We're building the next generation of data visualization.