How to Run a Postgres Docker Container on Oracle Cloud Infrastructure
Docker has revolutionized modern software infrastructure, pioneering an OS-level approach to virtualization known as "containers". Unlike traditional VMs which bundle the guest OS with apps, Docker enabled lighter-weight virtualization by leveraging existing Linux kernel capabilities like cgroups, namespaces, and union file systems.
This article provides an expert full-stack developer‘s perspective on running enterprise-grade Postgres database within a Docker container on Oracle Cloud Infrastructure (OCI).
We will dive deep into both the technical details and the big picture of combining these technologies for resilient, scalable data persistence aligned to today‘s microservices driven application architectures.
A Brief History of Containers and Docker
The concepts underlying Linux containers date all the way back to the late 1970s when Unix pioneered a fork+exec process model that prevented tampering across users. Building upon the chroot capability for isolation, FreeBSD later introduced jail containers in 2000 for partitioning users.
Inspired by these earlier OS-virtualization features, Docker debuted in 2013 and quickly popularized the ease of containers for packaging and distributing applications. Dictated by the philosophy of "Build Once, Run Anywhere", Docker offered portability across environments by incorporating only app binaries rather than needing guest OSs. This made containers extremely lightweight and fast compared to traditional VMs.
Some key aspects that sparked Docker‘s rapid emergence include:
Packaging – Docker introduced new tooling like Dockerfiles to reliably build container images that bundle apps with dependencies. This facilitated packaging software for distribution.
Composability – Containers promote decomposing apps into microservices composed via isolated interconnections. This aligns to modern trends around service-oriented architectures.
Isolation – Namespaces, control groups, and other isolation mechanisms were leveraged to allow high-density multi-tenancy while restricting access between containers.
Portability – Encapsulating just the app platform with no guest OS meant containers could smoothly run on any supporting Linux distribution without changes.
The software development ecosystem quickly rallied around Docker‘s approach to containers. Orchestrators like Kubernetes soon followed taking container scheduling and management to the next level. A vibrant tooling ecosystem continues evolving around the containerization paradigm.
PostgreSQL Database Overview
PostgreSQL‘s origins trace back to the POSTGRES project begun in 1986 at UC Berkeley. Building upon pioneering System R database research from IBM, Postgres sought to incorporate emerging SQL standards into an advanced open source relational database management system (RDBMS).
After decades of development by global open source contributors, PostgreSQL has become renowned as a fully featured enterprise-ready database system. Let‘s analyze what sets PostgreSQL apart from other open source alternatives:
ACID Compliance – Transactions satisfy critical properties like atomicity, consistency, isolation and durability. This guarantees reliability of database state across transactional operations.
MVCC – Multi-version concurrency control facilitates reader efficiency by isolating snapshot transactions from writer locking and changes.
Extensibility – Custom data types, functions, operators, aggregates etc allow PostgreSQL fitting to specialized use cases beyond conventional SQL.
Durability – Crash recovery utilizes write ahead logging for higher data integrity and consistency after system failures. This prevents corruption and loss unlike some database systems.
Combining these advanced capabilities enables PostgreSQL meeting demanding data persistence needs across industries from finance to healthcare and beyond. But being able to effectively leverage PostgreSQL for microservices driven architectures requires easing deployment complexity.
And that leads us to using Docker for running PostgreSQL….
Running PostgreSQL in a Docker Container
As discussed earlier, Docker revolutionized modern infrastructure through several key innovations. For a system as critical as PostgreSQL database persistence, Docker unlocks compelling advantages:
Portability – Tightly packaging the database server decouples it from particular Linux distro or kernel versions. This prevents environment induced failures.
Isolation – Containerization provides security boundaries limiting vulnerabilities. Resources consumed by database are precisely allocated as opposed to noisier neighbors in a traditional VM.
Scalability – Running PostgreSQL in containers maintains small lightweight footprint. This allows horizontally scaling out more database instances compared to bulky VMs.
Resilience – With containers promoting ephemeral infrastructure, failed containers are easily replaced with fresh ones rather than manual recovery. Immutable infrastructure reduces drift across container redeploys.
For maximum reliability and scale, Docker containers present the ideal path for deploying PostgreSQL alongside modern cloud-native applications.
Next let‘s dive into the hands-on details for deploying PostgreSQL inside a container on Oracle‘s cloud….
Complete Setup Details
In the following sections, we go through the full workflow for deploying PostgreSQL into a Docker container running on an Oracle Cloud Infrastructure (OCI) VM instance:
- Provisioning an Oracle VM Instance
- Configuring Network Security
- Installing Docker
- Running the PostgreSQL Container
- Accessing the Database
- Configuring for High Availability (HA)
- Performance Optimization and Tuning
- Integrating with Microservices
Provisioning an Oracle VM Instance
First, we need to create a VM within OCI to host the Docker container…
The key steps for this involve:
Launch small single core VM instance like
VM.Standard.E2.1.Micro
under Always Free tierChoose desired Oracle Linux image
Stick with default VCN and subnet
Once running, the VM will be the Docker host for our PostgreSQL container.
Configuring Network Security
With VM up, let‘s open firewall access to the PostgreSQL port by:
Adding ingress rule to default security list
Opening TCP port 5432 inbound from 0.0.0.0/0
This allows external connectivity to our database container.
Installing Docker
We next setup the Docker engine itself:
# Install latest docker engine
sudo yum install docker-engine
# Start docker and setup to start on reboot
sudo systemctl start docker
sudo systemctl enable docker
Now we‘re ready for launching our PostgreSQL container…
Running the PostgreSQL Container
Starting a containerized PostgreSQL instance looks like:
# Run container detached, mapping ports, setting creds
sudo docker run -d \
-p 5432:5432 \
-e POSTGRES_PASSWORD=mysecret \
--name postgres \
postgres
# Check container is running
sudo docker ps
This PostgreSQL server is now running isolated within the container but available on the host VM via standard port 5432.
With the database container operational, we can proceed to interacting with it.
Creating and Accessing the Database
Once Docker container running, we create a database via:
# Access interactive shell inside container
docker exec -it postgres bash
# Connect to Postgres CLI as default user
psql -U postgres
# Create our database
CREATE DATABASE mydb;
We install pgAdmin on our local machine and configure connection:
Host – Public IP of OCI VM instance
Port – 5432
Username – postgres
Password – mysecret (set earlier)
This allows interacting with the PostgreSQL database running inside Docker on OCI via standard graphical tooling like pgAdmin or DBeaver.
Configuring for High Availability
For improved resilience for a production use case, we should avoid depending on a single VM. Fortunately, Docker‘s lightweight footprint simplifies running active replicas.
Potential High Availability improvements include:
Multi-AZ containers – Stagger containers across multiple availability domains/fault domains within a region avoiding zone level failures knocking all instances offline.
Replication – Leverage Postgres streaming replication to ensure redundant synchronous commit log data propagation avoiding data loss.
Load balancing – Front container cluster with HAProxy to dispatch across healthy containers.
Orchestration – Further option is full orchestrator like Kubernetes managing failover detection and promotion minimizing downtime during outages.
Performance Optimization and Tuning
To optimize throughput for PostgreSQL workloads on OCI VMs:
Storage optimized shapes – Pick VM shapes like BM.DenseIO
tailored specifically for IOPS intensive databases.
Volume mounting – Attach higher performance block volumes to maximize disk throughput rather than default OS images.
PostgreSQL config tuning – Modifying postgresql.conf
settings like:
shared_buffers = #HIGHER
work_mem = #HIGHER
max_wal_size = #HIGHER
max_parallel_workers_per_gather = #HIGHER
Greatly accelerates queries by further utilizing available compute resources.
Integrating PostgreSQL with Microservices
Modern cloud-native applications embed persistence in backend services rather than separate data layer. This challenges traditional three-tier architectures requiring looser coupling.
Containers directly encourage building decentralized data models around microservicesOwn data rather than monolithic logical models. Docker environments give every service isolated access to fit its domain integrity needs.
PostgreSQL offers top performance and enterprise grade durability while simplifying embedding within microservices through Docker. Together they answer demands for cloud ready data architectures.
Conclusion
In this extensive guide, we took an expert full-stack developer‘s view on deploying PostgreSQL into a Docker container within OCI. Containers unlock excellent productivity for working with microservice oriented architectures. PostgreSQL brings battle tested enterprise-grade RDBMS providing ACID durability and transactional integrity on which to build the next generation of cloud-native data persistence.
By embracing modern paradigms like containers and microservices alongside stalwart open source data platforms like Postgres, developers build future facing skills that fully leverage today‘s cloud offerings like OCI.
What questions remain unanswered for you when it comes to integrating PostgreSQL and Docker? I welcome hearing your feedback below!