Skip to content

Instantly share code, notes, and snippets.

@michael-halim
Created March 15, 2023 06:25
Show Gist options
  • Save michael-halim/2d97ac0f7f7fbf0906077e86dd2ce9b9 to your computer and use it in GitHub Desktop.
Save michael-halim/2d97ac0f7f7fbf0906077e86dd2ce9b9 to your computer and use it in GitHub Desktop.
Deploy Django with PostgreSQL on Virtual Private Server (CentOS 8)

Version

  • CentOS 8
  • Django 4.1.2
  • PostgreSQL 14.6

References

# Login to VPS
ssh <username>@<ip_address>

# Get All Dependencies
sudo yum update
sudo yum upgrade

# Install Dependencies
sudo yum install python3-pip
sudo yum install postgresql postgresql-contrib
sudo yum install python39
dnf install libpq-devel 
dnf install python3-devel -y
sudo yum -y install https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
sudo dnf -qy module disable postgresql
sudo systemctl reboot
sudo yum install -y postgresql14-server postgresql14
sudo /usr/pgsql-14/bin/postgresql-14-setup initdb

# Enable PostgreSQL and Check Status
sudo systemctl enable --now postgresql-14
systemctl status postgresql-14

# Change User to 'postgres' because PostgreSQL has default username 
sudo -i -u postgres

# Open PostgreSQL and Change Password (Must Do This for Security Purposes)
psql
CREATE DATABASE <db_name>;
ALTER USER postgres WITH PASSWORD '<new_password>';
exit

# Apply Migrations and Migrate
cd /home/<user>/<repo_name>
python3 manage.py makemigrations
python3 manage.py migrate

# Change PostgreSQL Settings to Open Remotely from 3rd Party App like pgAdmin, HeidiSQL, etc
# /14/ is depends on the version of PostgreSQL
echo "
host 	all		all		0.0.0.0/0		md5
host	all		all		 ::/0	      md5
" | sudo tee -a /var/lib/pgsql/14/main/pg_hba.conf

# Change Listen Addresses in /etc/postgresql/14/main/postgresql.conf to '*'
nano /etc/postgresql/14/main/postgresql.conf
listen_addresses = '*'

# Add PostgreSQL Port to Firewall 
sudo firewall-cmd --zone=public --add-port=5432/tcp --permanent
sudo firewall-cmd --reload
sudo reboot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment