Ports are used to establish connections remotely between multiple nodes in a network to transfer data or perform some computational operations. PostgreSQL is generally running on the port number “5432” and the user can simply connect to the PostgreSQL server using this port. The platform allows the user to change its default port if somehow “5432” is not responding or is occupied elsewhere.
This guide will explain how to change the default port in PostgreSQL.
How to Change Default Port in PostgreSQL?
To change the port of the PostgreSQL, connect to the PostgreSQL database using the following query:
psql -U postgres
Running the above query will prompt the user to enter the master password for the Postgres user:
Use the following command to get all the data from the pg_settings view and use the WHERE clause to get the data about the port:
select * from pg_settings where name='port';
Running the above query displays the default port which is “5432” of the PostgreSQL database:
Use the following command to get the port for the database and the user to which you are connected:
\conninfo
Type the following command to get the location of the file where the default port is stored:
show config_file;
The above command displays the path of the file where the port is saved:
Quit the PostgreSQL and head into the data directory of the PostgreSQL from the local system:
cd C:\Program` Files\PostgreSQL\15\data
Find the port number from the “postgresql.conf” file:
cat postgresql.conf | findstr 'port'
The port on each of the files on which the PostgreSQL database is running is “5432” so it is the default port for the PostgreSQL:
Locate the “postgresql.conf” file from the local system and open it:
Locate the port number from the file and change it from “5432” to “6543” before saving it:
After saving the file, use the following command again to get the updated port number:
cat postgresql.conf | findstr 'port'
The above command displays the “6543” port number:
Open the “Run” application from the local system:
Type the “services.msc” and click on the “OK” button:
Locate the PostgreSQL file, select it, and click on the “Restart” button:
Once the service is restarted head inside PostgreSQL and type the following command:
select * from pg_settings where name='port';
The default port has been changed successfully as displayed in the screenshot below:
That’s all about changing the default port in the PostgreSQL database.
Conclusion
To change the default port in PostgreSQL, simply connect to the PostgreSQL server by providing the master password for the user. After that, get the specific data about the port from the pg_settings view to get the default port number on which it is running. Use the “show config_file” command to get the path of the file and then change the port number from that file. Restart the service from the “service.msc” application and check the updated default port number.