Postgresql yml and landing page

This commit is contained in:
2026-04-16 00:17:03 +03:00
parent bd55228db4
commit c80f7db74c
9 changed files with 1718 additions and 1 deletions

128
README.md
View File

@@ -1,3 +1,131 @@
# topstore-server # topstore-server
TopStore server setup of postgresql in docker, automation scripts, landing page and adding more as it do progress TopStore server setup of postgresql in docker, automation scripts, landing page and adding more as it do progress
# Landing Page
A professional, high-performance landing page designed for a dual-purpose automotive business (parts retail and mechanical servicing). The site features a clean, "Inter" font-driven aesthetic with a bold red-and-dark-grey color palette.
## Core Features
* Bilingual Support (RO/EN): Full site translation between Romanian and English using a data-attribute-driven JavaScript system.
* Smart Language Detection: Automatically detects the users browser language on first visit and remembers preferences via localStorage.
* Optimized Mobile Experience: Fully responsive grid system that collapses into a single-column stack for mobile devices.
* Conversion-Focused UI:
* Prominent Hero CTA buttons.
* Custom-built Phone Selection Modal to direct users to specific service lines.
* "Tap-to-call" and "Tap-to-email" integration for mobile users.
* Dynamic Elements: Auto-updating copyright year and smooth "fade-in" transitions for translated text to prevent "Flash of Unstyled Content" (FOUC).
## Technical Stack
* HTML5/CSS3: Utilizes CSS Variables for easy branding updates and a CSS Grid/Flexbox layout.
* JavaScript (Vanilla): Lightweight script handles the modal logic and the translation engine without external dependencies.
* Google Fonts: Integrated "Inter" typeface with multiple weights (400, 700, 900).
## File Structure
* index.html: The semantic structure containing both English and Romanian strings in data- attributes.
* style.css: Modern styling including a "glassmorphism" modal overlay and responsive media queries.
* /assets: Recommended directory for the company logo and favicon.
## Setup & Customization
1. Map Integration: Update the iframe src attributes in the contact-info section with your specific Google Maps embed codes.
2. Contact Details: Replace the phone numbers and email address in both the contact-details and modal-overlay sections.
3. Images: The hero background is currently linked to a high-quality Unsplash image; this can be swapped in style.css under the .hero class.
# Potgres 10 Docker for Trade software
A robust, containerized Postgres 10 setup designed for production environments. It includes automated hourly/daily backups, custom configuration management, and a comprehensive management script.
## Quick Start
Configure Environment: Create a .env file in the root directory (see Environment Variables).
Run Setup: Initialize directories and permissions. This will create and set the right permissions for `config`, `pgdata` and `backups` folders:
```cmd
./manage_db.sh setup
```
Make sure that the right folders are created. Inside `config/` there must be `pg_hba.conf` and `postgresql.conf`. The files are created based on [config_template](postgres_10_docker/config_template/) folder or from docker template files.
Start Services: Launch the database and backup containers:
```cmd
./manage_db.sh run
```
## Features
* **Database:** `PostgreSQL 10` with persisted data in `./pgdata`.
* **Custom Config:** Uses external `postgresql.conf` and `pg_hba.conf` for fine-tuning.
* **Automatic Backups:** Scheduled backups using `postgres-backup-local` with configurable retention.
* **Timezone Sync:** Containers automatically sync with the host system time.
* **Health Checks:** Backup service waits for the database to be fully "Ready" before starting.
* **Security:** Configuration files are mounted as Read-Only inside the container.
## Project Structure
* `manage_db.sh`: The main entry point for managing the stack.
* `config/`: Contains PostgreSQL configuration files (generated during setup).
* `pgdata/`: Persistent storage for the database (Postgres UID 999).
* `backups/`: Location for compressed .sql.gz backup files.
## Environment Variables (.env)
Ensure the following variables are defined in your `.env` file:
* **POSTGRES_USER**: Database administrator username - `admin`
* **POSTGRES_PASSWORD**: Database administrator password - `securepassword`
* **POSTGRES_DB**: Name of the primary database - `db`
* **TZ**: System timezone `UTC`
* **BACKUP_SCHEDULE**: Cron schedule for backups - `0 0 * * * (Daily)`
* **BACKUP_RETENTION_DAYS**: How many days to keep backups - `7`
## Management Script Usage
The `manage_db.sh` script simplifies common Docker commands:
Command Description:
* Creates folders, sets permissions, and extracts config templates.
```cmd
./manage_db.sh setup
```
* Starts all services in detached mode.
```cmd
./manage_db.sh run
```
* Stops the containers.
```cmd
./manage_db.sh stop
```
* Shows running status and resource usage (CPU/RAM).
```cmd
./manage_db.sh status
```
* Tails logs for all services.
```cmd
./manage_db.sh logs
```
* Jumps directly into the Postgres SQL prompt.
```cmd
./manage_db.sh psql
```
* Triggers a manual backup immediately.
```cmd
./manage_db.sh backup
```
* Restores a database from a .gz or .dump file.
```cmd
./manage_db.sh restore <file>
```
## Security & Permissions
During the setup phase, the script applies `chown -R 999:999` to the data and config folders. This matches the internal postgres user ID used by the official Docker image, ensuring the container has the necessary rights to write data and read configurations.

Binary file not shown.

After

Width:  |  Height:  |  Size: 299 KiB

290
landing_page/index.html Normal file
View File

@@ -0,0 +1,290 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title class="lang"
data-en="TOP STORE | Car Parts & Servicing"
data-ro="TOP STORE | Piese auto și service">
TOP STORE | Car Parts & Servicing
</title>
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700;900&display=swap" rel="stylesheet">
</head>
<body>
<section class="hero">
<div class="lang-switcher">
<button onclick="setLanguage('ro')" id="btn-ro" class="lang-btn">RO</button>
<button onclick="setLanguage('en')" id="btn-en" class="lang-btn">EN</button>
</div>
<div class="container">
<img src="assets/logo.png" alt="TOP STORE Logo" class="main-logo">
<h1 class="lang"
data-en="YOUR ULTIMATE ONE-STOP<br>AUTOMOTIVE HUB"
data-ro="HUB-UL TĂU COMPLET PENTRU<br>AUTOMOBILE">
YOUR ULTIMATE ONE-STOP<br>AUTOMOTIVE HUB
</h1>
<p class="lang sub-headline"
data-en="To secure a servicing window or inquire about a car component, please call us. Our experts are standing by."
data-ro="Pentru a rezerva o programare sau pentru a solicita informații despre o componentă auto, vă rugăm să ne sunați. Experții noștri vă stau la dispoziție.">
To secure a servicing window or inquire about a car component, please call us. Our experts are standing by.
</p>
<div class="cta-buttons">
<button onclick="openModal()" class="btn btn-red lang"
data-en="CALL TO ORDER COMPONENTS"
data-ro="SANAȚI PENTRU A COMANDA COMPONENTE">
CALL TO ORDER COMPONENTS
</button>
<button onclick="openModal()" class="btn btn-dark lang"
data-en="CALL TO BOOK SERVICING"
data-ro="SUNAȚI PENTRU A PROGRAMA DESERVIREA MAȘINII">
CALL TO BOOK SERVICING
</button>
</div>
</div>
</section>
<section class="services">
<div class="container grid">
<div class="service-card">
<h2 class="lang"
data-en="GENUINE & PERFORMANCE PARTS"
data-ro="PIESE ORIGINALE ȘI DE PERFORMANȚĂ">
GENUINE & PERFORMANCE PARTS
</h2>
<div class="icons">⚙️ 🔌 🏎️</div>
<p class="lang"
data-en="High-quality components for every make and model."
data-ro="Componente de înaltă calitate pentru fiecare marcă și model.">
High-quality components for every make and model.
</p>
</div>
<div class="service-card">
<h2 class="lang"
data-en="EXPERT REPAIR & SERVICING"
data-ro="REPARAȚII ȘI SERVICE DE LA EXPERȚI">
EXPERT REPAIR & SERVICING
</h2>
<div class="icons">🔧 💻 🛠️</div>
<p class="lang"
data-en="Professional maintenance and diagnostic services."
data-ro="Servicii profesionale de întreținere și diagnosticare.">
Professional maintenance and diagnostic services.
</p>
</div>
</div>
</section>
<section class="contact-info">
<div class="container">
<div class="grid">
<div class="map-box">
<h2 class="lang"
data-en="Car Parts"
data-ro="Piese auto">
Car Parts
</h2>
<iframe
src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d3622.4640986134714!2d28.63462057793557!3d47.14254155055245!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x40cbd00b84eaf29b%3A0xdb92849f2bb67bf6!2sTop%20Store!5e0!3m2!1sen!2sus!4v1776243809003!5m2!1sen!2sus"
width="100%" height="250" style="border:0; border-radius: 8px;" allowfullscreen="" loading="lazy">
</iframe>
</div>
<div class="map-box">
<h2 class="lang"
data-en="Car Service"
data-ro="Service auto">
Car Service
</h2>
<iframe
src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d3728.7652298696!2d28.639850982165633!3d47.14033133574228!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x40cbd1004f490f65%3A0xe4971bf2049d05ec!2sAuto%20service!5e0!3m2!1sen!2sus!4v1776243851000!5m2!1sen!2sus"
width="100%" height="250" style="border:0; border-radius: 8px;" allowfullscreen="" loading="lazy">
</iframe>
</div>
</div>
<div class="contact-details">
<h3 class="lang"
data-en="CONTACT US"
data-ro="CONTACTAŢI-NE">
CONTACT US
</h3>
<div class="contact-row">
<div class="contact-item">
<span class="icon">📞</span>
<div>
<p class="label lang"
data-en="CALL FOR BOOKING"
data-ro="SUNAȚI PENTRU REZERVĂRI">
CALL FOR BOOKING
</p>
<div class="cta-buttons">
<a href="tel:+373 683 10 310" class="btn btn-dark-outline">+373 683 10 310</a>
<a href="tel:+373 794 76 060" class="btn btn-dark-outline">+373 794 76 060</a>
</div>
</div>
</div>
<div class="contact-item">
<span class="icon">📧</span>
<div>
<p class="label lang"
class="lang"
data-en="EMAIL US"
data-ro="TRIMITEȚI-NE UN E-MAIL">
EMAIL US
</p>
<div class="cta-buttons">
<a href="mailto:topstoreom@gmail.com" class="btn btn-dark-outline">topstoreom@gmail.com</a>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Popup handling -->
<div id="phonePopup" class="modal-overlay">
<span class="close-icon" onclick="closeModal()">&times;</span>
<div class="modal-body">
<h2 class="lang"
data-en="SELECT PHONE NUMBER"
data-ro="SELECTAȚI NUMĂRUL DE TELEFON">
SELECT PHONE NUMBER
</h2>
<p class="lang"
data-en="Our experts are available at both lines:"
data-ro="Experții noștri sunt disponibili pe ambele linii:">
Our experts are available at both lines:
</p>
<div class="modal-phone-grid">
<a href="tel:+373 683 10 310" class="btn btn-dark-outline lang"
data-en="📞 LINE 1: +373 683 10 310"
data-ro="📞 LINIA 1: +373 683 10 310">
📞 LINE 1: +373 683 10 310
</a>
<a href="tel:+373 794 76 060" class="btn btn-dark-outline lang"
class="lang"
data-en="📞 LINE 2: +373 794 76 060"
data-ro="📞 LINIA 2: +373 794 76 060">
📞 LINE 2: +373 794 76 060
</a>
</div>
<button onclick="closeModal()" class="btn btn-link">CANCEL</button>
</div>
</div>
</div>
<script>
// Define your site's default language for first-time visitors
const DEFAULT_LANG = 'ro';
function setLanguage(lang) {
// Find all elements with the 'lang' class
const elements = document.querySelectorAll('.lang');
elements.forEach(el => {
// Get the translation from the data attribute
const translation = el.getAttribute(`data-${lang}`);
if (translation) {
el.innerHTML = translation;
}
// Make the element visible now that it has the right text
el.classList.add('lang-loaded');
});
// Update button styles
document.querySelectorAll('.lang-btn').forEach(btn => btn.classList.remove('active'));
const activeBtn = document.getElementById(`btn-${lang}`);
if(activeBtn) activeBtn.classList.add('active');
// Save preference to local storage
localStorage.setItem('preferredLang', lang);
}
(function initLang() {
// Priority 1: Saved preference
// Priority 2: Browser language (Optional extra)
// Priority 3: Your DEFAULT_LANG
const saved = localStorage.getItem('preferredLang');
const browserLang = navigator.language.split('-')[0]; // returns 'ro' or 'en'
const supported = ['ro', 'en'];
const finalDefault = supported.includes(browserLang) ? browserLang : DEFAULT_LANG;
const userLang = saved || finalDefault;
// Use DOMContentLoaded to ensure elements exist before we touch them
document.addEventListener("DOMContentLoaded", () => {
setLanguage(userLang);
// Also handle the year here to keep init organized
const yearSpan = document.getElementById("current-year");
if(yearSpan) yearSpan.textContent = new Date().getFullYear();
});
})();
// Optimized Startup
document.addEventListener("DOMContentLoaded", () => {
// Set Year
const yearSpan = document.getElementById("current-year");
if(yearSpan) yearSpan.textContent = new Date().getFullYear();
// Immediate Language Check
const savedLang = localStorage.getItem('preferredLang') || 'en';
setLanguage(savedLang);
});
// Check for saved language on page load
window.onload = () => {
// Set the Year automatically
const yearSpan = document.getElementById("current-year");
if(yearSpan) {
yearSpan.textContent = new Date().getFullYear();
}
// Load the saved language or default to 'en'
const savedLang = localStorage.getItem('preferredLang') || 'en';
setLanguage(savedLang);
};
// This is even safer if you have multiple places where the year appears
document.querySelectorAll('.year').forEach(el => {
el.innerText = new Date().getFullYear();
});
// Modal - popup handling
// Open popup
function openModal() {
document.getElementById('phonePopup').style.display = 'flex';
}
// Close popup
function closeModal() {
document.getElementById('phonePopup').style.display = 'none';
}
// Close if user clicks outside the white box
window.onclick = function(event) {
const modal = document.getElementById('phonePopup');
if (event.target == modal) {
closeModal();
}
}
</script>
<footer>
<p>
&copy; <span id="current-year"></span>
<span class="lang"
data-en="TOP STORE. All Rights Reserved."
data-ro="TOP STORE. Toate drepturile rezervate.">
TOP STORE. All Rights Reserved.
</p>
</footer>
</body>
</html>

313
landing_page/style.css Normal file
View File

@@ -0,0 +1,313 @@
:root {
--primary-red: #E31E24;
--dark-grey: #1a1a1a;
--grey-text: #666;
--light-grey: #f4f4f4;
--white: #ffffff;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Inter', sans-serif;
line-height: 1.6;
color: var(--dark-grey);
background-color: var(--white);
}
.container {
max-width: 1100px;
margin: 0 auto;
padding: 0 20px;
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 30px;
}
/* Hero Section */
.hero {
padding: 80px 0;
text-align: center;
background: linear-gradient(rgba(255,255,255,0.92), rgba(255,255,255,0.92)), url('https://images.unsplash.com/photo-1486262715619-67b85e0b08d3?q=80&w=2000') center/cover;
}
.main-logo {
width: 180px;
margin-bottom: 25px;
}
h1 {
font-size: 3rem;
font-weight: 900;
margin-bottom: 15px;
line-height: 1.1;
}
.sub-headline {
font-size: 1.1rem;
max-width: 650px;
margin: 0 auto 35px;
color: #444;
}
/* Universal Button Styles */
.cta-buttons {
display: flex;
flex-wrap: wrap;
gap: 15px;
}
.hero .cta-buttons {
justify-content: center;
}
.btn {
padding: 14px 28px;
text-decoration: none;
font-weight: 700;
border-radius: 6px;
transition: all 0.3s ease;
display: inline-block;
font-size: 0.95rem;
}
.btn-red { background: var(--primary-red); color: white; }
.btn-red:hover { background: #c1171c; transform: translateY(-2px); }
.btn-dark { background: var(--dark-grey); color: white; }
.btn-dark:hover { background: #333; transform: translateY(-2px); }
.btn-dark-outline {
background: var(--dark-grey);
color: white;
}
.btn-dark-outline:hover {
background: var(--primary-red);
}
/* Services Section */
.services {
padding: 70px 0;
background: var(--light-grey);
}
.service-card {
background: white;
padding: 40px;
border-radius: 12px;
border-top: 6px solid var(--primary-red);
text-align: center;
box-shadow: 0 10px 30px rgba(0,0,0,0.05);
}
.service-card h2 { margin-bottom: 10px; font-size: 1.4rem; }
.icons { font-size: 2.5rem; margin: 15px 0; }
/* Contact & Maps Section */
.contact-info { padding: 80px 0; }
.map-box h2 {
font-size: 1.4rem;
margin-bottom: 15px;
font-weight: 700;
}
.contact-details {
margin-top: 60px;
}
.contact-details h3 {
font-size: 1.8rem;
font-weight: 900;
margin-bottom: 25px;
}
.contact-row {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.contact-item {
flex: 1;
min-width: 320px;
display: flex;
align-items: center;
background: var(--light-grey);
padding: 25px;
border-radius: 12px;
border-left: 6px solid var(--primary-red);
}
.contact-item .icon {
font-size: 2.2rem;
margin-right: 20px;
}
.label {
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 1px;
font-weight: 900;
color: var(--grey-text);
margin-bottom: 5px;
}
/* Hide translatable elements until the script runs */
.lang {
opacity: 0;
transition: opacity 0.2s ease-in;
}
/* This class will be added by JS once the language is set */
.lang-loaded {
opacity: 1;
}
.lang-switcher {
position: absolute;
top: 20px;
right: 20px;
display: flex;
gap: 10px;
z-index: 1001;
}
.lang-btn {
background: rgba(0,0,0,0.5);
border: 1px solid #fff;
color: white;
padding: 5px 10px;
cursor: pointer;
font-weight: bold;
border-radius: 4px;
transition: 0.3s;
}
.lang-btn.active {
background: var(--primary-red);
border-color: var(--primary-red);
}
.lang-btn:hover {
background: var(--primary-red);
}
/* Footer */
footer {
text-align: center;
padding: 30px;
background: var(--dark-grey);
color: #999;
font-size: 0.85rem;
}
/* Responsive Design */
@media (max-width: 850px) {
.grid { grid-template-columns: 1fr; }
.contact-row { flex-direction: column; }
.contact-item { width: 100%; }
h1 { font-size: 2.2rem; }
.hero .cta-buttons { flex-direction: column; align-items: center; }
.btn { width: 100%; text-align: center; }
}
/* MODAL STYLES */
/* Styling the phone buttons inside the modal */
.modal-phone-grid {
display: flex;
flex-direction: column;
gap: 15px;
margin: 25px 0;
}
.modal-phone-grid .btn {
width: 100%;
text-align: center;
font-size: 1.1rem;
padding: 15px;
}
/* A clean button that looks like a link for the "Close" action */
.btn-link {
background: none;
border: none;
color: #888;
font-weight: 700;
cursor: pointer;
text-decoration: underline;
margin-top: 10px;
}
.btn-link:hover {
color: var(--primary-red);
}
/* Ensure the modal overlay covers the screen professionally */
.modal-overlay {
display: none; /* Changed to flex by JavaScript when opened */
position: fixed;
z-index: 9999;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.85);
backdrop-filter: blur(4px);
/* These two only work when display is flex */
align-items: center;
justify-content: center;
}
/* The 'X' in the corner of the modal */
.close-icon {
position: absolute;
top: 15px;
right: 20px;
font-size: 28px;
font-weight: bold;
color: #888;
cursor: pointer;
line-height: 1;
transition: color 0.2s ease;
}
.close-icon:hover {
color: var(--primary-red); /* Highlights red when you hover to close */
}
/* The container for the content inside the white box */
.modal-body {
padding: 10px 0;
text-align: center;
}
/* If the text is sitting directly on the dark overlay */
.modal-body h2 {
font-size: 1.8rem;
font-weight: 900;
margin-bottom: 10px;
text-transform: uppercase;
color: #ffffff; /* Brighter white for the title */
letter-spacing: 1px;
}
.modal-body p {
font-size: 1.1rem;
color: #e0e0e0; /* Brighter light grey for the description */
margin-bottom: 25px;
font-weight: 400;
}
/* Optional: Add a slight glow to the title to make it pop */
.modal-body h2 {
text-shadow: 0 2px 10px rgba(255, 255, 255, 0.1);
}

15
postgres_10_docker/.env Normal file
View File

@@ -0,0 +1,15 @@
# Database Credentials
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres
POSTGRES_DB=db
# Timezone (Matches your system, e.g., Europe/Chisinau or America/New_York)
TZ=Europe/Chisinau
# Backup Settings
# Options: @hourly, @daily, @weekly, @monthly
# BACKUP_SCHEDULE=@daily
# Cron Schedule: Minute Hour Day Month Day_of_Week
# This example runs every night at 03:15 AM
BACKUP_SCHEDULE="0 1 * * *"
BACKUP_RETENTION_DAYS=30

View File

@@ -0,0 +1,95 @@
# PostgreSQL Client Authentication Configuration File
# ===================================================
#
# Refer to the "Client Authentication" section in the PostgreSQL
# documentation for a complete description of this file. A short
# synopsis follows.
#
# This file controls: which hosts are allowed to connect, how clients
# are authenticated, which PostgreSQL user names they can use, which
# databases they can access. Records take one of these forms:
#
# local DATABASE USER METHOD [OPTIONS]
# host DATABASE USER ADDRESS METHOD [OPTIONS]
# hostssl DATABASE USER ADDRESS METHOD [OPTIONS]
# hostnossl DATABASE USER ADDRESS METHOD [OPTIONS]
#
# (The uppercase items must be replaced by actual values.)
#
# The first field is the connection type: "local" is a Unix-domain
# socket, "host" is either a plain or SSL-encrypted TCP/IP socket,
# "hostssl" is an SSL-encrypted TCP/IP socket, and "hostnossl" is a
# plain TCP/IP socket.
#
# DATABASE can be "all", "sameuser", "samerole", "replication", a
# database name, or a comma-separated list thereof. The "all"
# keyword does not match "replication". Access to replication
# must be enabled in a separate record (see example below).
#
# USER can be "all", a user name, a group name prefixed with "+", or a
# comma-separated list thereof. In both the DATABASE and USER fields
# you can also write a file name prefixed with "@" to include names
# from a separate file.
#
# ADDRESS specifies the set of hosts the record matches. It can be a
# host name, or it is made up of an IP address and a CIDR mask that is
# an integer (between 0 and 32 (IPv4) or 128 (IPv6) inclusive) that
# specifies the number of significant bits in the mask. A host name
# that starts with a dot (.) matches a suffix of the actual host name.
# Alternatively, you can write an IP address and netmask in separate
# columns to specify the set of hosts. Instead of a CIDR-address, you
# can write "samehost" to match any of the server's own IP addresses,
# or "samenet" to match any address in any subnet that the server is
# directly connected to.
#
# METHOD can be "trust", "reject", "md5", "password", "scram-sha-256",
# "gss", "sspi", "ident", "peer", "pam", "ldap", "radius" or "cert".
# Note that "password" sends passwords in clear text; "md5" or
# "scram-sha-256" are preferred since they send encrypted passwords.
#
# OPTIONS are a set of options for the authentication in the format
# NAME=VALUE. The available options depend on the different
# authentication methods -- refer to the "Client Authentication"
# section in the documentation for a list of which options are
# available for which authentication methods.
#
# Database and user names containing spaces, commas, quotes and other
# special characters must be quoted. Quoting one of the keywords
# "all", "sameuser", "samerole" or "replication" makes the name lose
# its special character, and just match a database or username with
# that name.
#
# This file is read on server startup and when the server receives a
# SIGHUP signal. If you edit the file on a running system, you have to
# SIGHUP the server for the changes to take effect, run "pg_ctl reload",
# or execute "SELECT pg_reload_conf()".
#
# Put your actual configuration here
# ----------------------------------
#
# If you want to allow non-local connections, you need to add more
# "host" records. In that case you will also need to make PostgreSQL
# listen on a non-local interface via the listen_addresses
# configuration parameter, or via the -i or -h command line switches.
# CAUTION: Configuring the system for local "trust" authentication
# allows any local user to connect as any PostgreSQL user, including
# the database superuser. If you do not trust all your local users,
# use another authentication method.
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
host all all ::1/128 trust
# Allow replication connections from localhost, by a user with the
# replication privilege.
local replication all trust
host replication all 127.0.0.1/32 trust
host replication all ::1/128 trust
host all all all md5

View File

@@ -0,0 +1,663 @@
# -----------------------------
# PostgreSQL configuration file
# -----------------------------
#
# This file consists of lines of the form:
#
# name = value
#
# (The "=" is optional.) Whitespace may be used. Comments are introduced with
# "#" anywhere on a line. The complete list of parameter names and allowed
# values can be found in the PostgreSQL documentation.
#
# The commented-out settings shown in this file represent the default values.
# Re-commenting a setting is NOT sufficient to revert it to the default value;
# you need to reload the server.
#
# This file is read on server startup and when the server receives a SIGHUP
# signal. If you edit the file on a running system, you have to SIGHUP the
# server for the changes to take effect, run "pg_ctl reload", or execute
# "SELECT pg_reload_conf()". Some parameters, which are marked below,
# require a server shutdown and restart to take effect.
#
# Any parameter can also be given as a command-line option to the server, e.g.,
# "postgres -c log_connections=on". Some parameters can be changed at run time
# with the "SET" SQL command.
#
# Memory units: kB = kilobytes Time units: ms = milliseconds
# MB = megabytes s = seconds
# GB = gigabytes min = minutes
# TB = terabytes h = hours
# d = days
#------------------------------------------------------------------------------
# FILE LOCATIONS
#------------------------------------------------------------------------------
# The default values of these variables are driven from the -D command-line
# option or PGDATA environment variable, represented here as ConfigDir.
#data_directory = 'ConfigDir' # use data in another directory
# (change requires restart)
#hba_file = 'ConfigDir/pg_hba.conf' # host-based authentication file
# (change requires restart)
#ident_file = 'ConfigDir/pg_ident.conf' # ident configuration file
# (change requires restart)
# If external_pid_file is not explicitly set, no extra PID file is written.
#external_pid_file = '' # write an extra PID file
# (change requires restart)
#------------------------------------------------------------------------------
# CONNECTIONS AND AUTHENTICATION
#------------------------------------------------------------------------------
# - Connection Settings -
listen_addresses = '*'
# comma-separated list of addresses;
# defaults to 'localhost'; use '*' for all
# (change requires restart)
#port = 5432 # (change requires restart)
max_connections = 100 # (change requires restart)
#superuser_reserved_connections = 3 # (change requires restart)
#unix_socket_directories = '/var/run/postgresql' # comma-separated list of directories
# (change requires restart)
#unix_socket_group = '' # (change requires restart)
#unix_socket_permissions = 0777 # begin with 0 to use octal notation
# (change requires restart)
#bonjour = off # advertise server via Bonjour
# (change requires restart)
#bonjour_name = '' # defaults to the computer name
# (change requires restart)
# - Security and Authentication -
#authentication_timeout = 1min # 1s-600s
#ssl = off
#ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers
#ssl_prefer_server_ciphers = on
#ssl_ecdh_curve = 'prime256v1'
#ssl_dh_params_file = ''
#ssl_cert_file = 'server.crt'
#ssl_key_file = 'server.key'
#ssl_ca_file = ''
#ssl_crl_file = ''
#password_encryption = md5 # md5 or scram-sha-256
#db_user_namespace = off
#row_security = on
# GSSAPI using Kerberos
#krb_server_keyfile = ''
#krb_caseins_users = off
# - TCP Keepalives -
# see "man 7 tcp" for details
#tcp_keepalives_idle = 0 # TCP_KEEPIDLE, in seconds;
# 0 selects the system default
#tcp_keepalives_interval = 0 # TCP_KEEPINTVL, in seconds;
# 0 selects the system default
#tcp_keepalives_count = 0 # TCP_KEEPCNT;
# 0 selects the system default
#------------------------------------------------------------------------------
# RESOURCE USAGE (except WAL)
#------------------------------------------------------------------------------
# - Memory -
shared_buffers = 128MB # min 128kB
# (change requires restart)
#huge_pages = try # on, off, or try
# (change requires restart)
#temp_buffers = 8MB # min 800kB
#max_prepared_transactions = 0 # zero disables the feature
# (change requires restart)
# Caution: it is not advisable to set max_prepared_transactions nonzero unless
# you actively intend to use prepared transactions.
#work_mem = 4MB # min 64kB
#maintenance_work_mem = 64MB # min 1MB
#replacement_sort_tuples = 150000 # limits use of replacement selection sort
#autovacuum_work_mem = -1 # min 1MB, or -1 to use maintenance_work_mem
#max_stack_depth = 2MB # min 100kB
dynamic_shared_memory_type = posix # the default is the first option
# supported by the operating system:
# posix
# sysv
# windows
# mmap
# use none to disable dynamic shared memory
# (change requires restart)
# - Disk -
#temp_file_limit = -1 # limits per-process temp file space
# in kB, or -1 for no limit
# - Kernel Resource Usage -
#max_files_per_process = 1000 # min 25
# (change requires restart)
#shared_preload_libraries = '' # (change requires restart)
# - Cost-Based Vacuum Delay -
#vacuum_cost_delay = 0 # 0-100 milliseconds
#vacuum_cost_page_hit = 1 # 0-10000 credits
#vacuum_cost_page_miss = 10 # 0-10000 credits
#vacuum_cost_page_dirty = 20 # 0-10000 credits
#vacuum_cost_limit = 200 # 1-10000 credits
# - Background Writer -
#bgwriter_delay = 200ms # 10-10000ms between rounds
#bgwriter_lru_maxpages = 100 # 0-1000 max buffers written/round
#bgwriter_lru_multiplier = 2.0 # 0-10.0 multiplier on buffers scanned/round
#bgwriter_flush_after = 512kB # measured in pages, 0 disables
# - Asynchronous Behavior -
#effective_io_concurrency = 1 # 1-1000; 0 disables prefetching
#max_worker_processes = 8 # (change requires restart)
#max_parallel_workers_per_gather = 2 # taken from max_parallel_workers
#max_parallel_workers = 8 # maximum number of max_worker_processes that
# can be used in parallel queries
#old_snapshot_threshold = -1 # 1min-60d; -1 disables; 0 is immediate
# (change requires restart)
#backend_flush_after = 0 # measured in pages, 0 disables
#------------------------------------------------------------------------------
# WRITE AHEAD LOG
#------------------------------------------------------------------------------
# - Settings -
#wal_level = replica # minimal, replica, or logical
# (change requires restart)
#fsync = on # flush data to disk for crash safety
# (turning this off can cause
# unrecoverable data corruption)
#synchronous_commit = on # synchronization level;
# off, local, remote_write, remote_apply, or on
#wal_sync_method = fsync # the default is the first option
# supported by the operating system:
# open_datasync
# fdatasync (default on Linux and FreeBSD)
# fsync
# fsync_writethrough
# open_sync
#full_page_writes = on # recover from partial page writes
#wal_compression = off # enable compression of full-page writes
#wal_log_hints = off # also do full page writes of non-critical updates
# (change requires restart)
#wal_buffers = -1 # min 32kB, -1 sets based on shared_buffers
# (change requires restart)
#wal_writer_delay = 200ms # 1-10000 milliseconds
#wal_writer_flush_after = 1MB # measured in pages, 0 disables
#commit_delay = 0 # range 0-100000, in microseconds
#commit_siblings = 5 # range 1-1000
# - Checkpoints -
#checkpoint_timeout = 5min # range 30s-1d
#max_wal_size = 1GB
#min_wal_size = 80MB
#checkpoint_completion_target = 0.5 # checkpoint target duration, 0.0 - 1.0
#checkpoint_flush_after = 256kB # measured in pages, 0 disables
#checkpoint_warning = 30s # 0 disables
# - Archiving -
#archive_mode = off # enables archiving; off, on, or always
# (change requires restart)
#archive_command = '' # command to use to archive a logfile segment
# placeholders: %p = path of file to archive
# %f = file name only
# e.g. 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f'
#archive_timeout = 0 # force a logfile segment switch after this
# number of seconds; 0 disables
#------------------------------------------------------------------------------
# REPLICATION
#------------------------------------------------------------------------------
# - Sending Server(s) -
# Set these on the master and on any standby that will send replication data.
#max_wal_senders = 10 # max number of walsender processes
# (change requires restart)
#wal_keep_segments = 0 # in logfile segments, 16MB each; 0 disables
#wal_sender_timeout = 60s # in milliseconds; 0 disables
#max_replication_slots = 10 # max number of replication slots
# (change requires restart)
#track_commit_timestamp = off # collect timestamp of transaction commit
# (change requires restart)
# - Master Server -
# These settings are ignored on a standby server.
#synchronous_standby_names = '' # standby servers that provide sync rep
# method to choose sync standbys, number of sync standbys,
# and comma-separated list of application_name
# from standby(s); '*' = all
#vacuum_defer_cleanup_age = 0 # number of xacts by which cleanup is delayed
# - Standby Servers -
# These settings are ignored on a master server.
#hot_standby = on # "off" disallows queries during recovery
# (change requires restart)
#max_standby_archive_delay = 30s # max delay before canceling queries
# when reading WAL from archive;
# -1 allows indefinite delay
#max_standby_streaming_delay = 30s # max delay before canceling queries
# when reading streaming WAL;
# -1 allows indefinite delay
#wal_receiver_status_interval = 10s # send replies at least this often
# 0 disables
#hot_standby_feedback = off # send info from standby to prevent
# query conflicts
#wal_receiver_timeout = 60s # time that receiver waits for
# communication from master
# in milliseconds; 0 disables
#wal_retrieve_retry_interval = 5s # time to wait before retrying to
# retrieve WAL after a failed attempt
# - Subscribers -
# These settings are ignored on a publisher.
#max_logical_replication_workers = 4 # taken from max_worker_processes
# (change requires restart)
#max_sync_workers_per_subscription = 2 # taken from max_logical_replication_workers
#------------------------------------------------------------------------------
# QUERY TUNING
#------------------------------------------------------------------------------
# - Planner Method Configuration -
#enable_bitmapscan = on
#enable_hashagg = on
#enable_hashjoin = on
#enable_indexscan = on
#enable_indexonlyscan = on
#enable_material = on
#enable_mergejoin = on
#enable_nestloop = on
#enable_seqscan = on
#enable_sort = on
#enable_tidscan = on
# - Planner Cost Constants -
#seq_page_cost = 1.0 # measured on an arbitrary scale
#random_page_cost = 4.0 # same scale as above
#cpu_tuple_cost = 0.01 # same scale as above
#cpu_index_tuple_cost = 0.005 # same scale as above
#cpu_operator_cost = 0.0025 # same scale as above
#parallel_tuple_cost = 0.1 # same scale as above
#parallel_setup_cost = 1000.0 # same scale as above
#min_parallel_table_scan_size = 8MB
#min_parallel_index_scan_size = 512kB
#effective_cache_size = 4GB
# - Genetic Query Optimizer -
#geqo = on
#geqo_threshold = 12
#geqo_effort = 5 # range 1-10
#geqo_pool_size = 0 # selects default based on effort
#geqo_generations = 0 # selects default based on effort
#geqo_selection_bias = 2.0 # range 1.5-2.0
#geqo_seed = 0.0 # range 0.0-1.0
# - Other Planner Options -
#default_statistics_target = 100 # range 1-10000
#constraint_exclusion = partition # on, off, or partition
#cursor_tuple_fraction = 0.1 # range 0.0-1.0
#from_collapse_limit = 8
#join_collapse_limit = 8 # 1 disables collapsing of explicit
# JOIN clauses
#force_parallel_mode = off
#------------------------------------------------------------------------------
# ERROR REPORTING AND LOGGING
#------------------------------------------------------------------------------
# - Where to Log -
#log_destination = 'stderr' # Valid values are combinations of
# stderr, csvlog, syslog, and eventlog,
# depending on platform. csvlog
# requires logging_collector to be on.
# This is used when logging to stderr:
#logging_collector = off # Enable capturing of stderr and csvlog
# into log files. Required to be on for
# csvlogs.
# (change requires restart)
# These are only used if logging_collector is on:
#log_directory = 'log' # directory where log files are written,
# can be absolute or relative to PGDATA
#log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log' # log file name pattern,
# can include strftime() escapes
#log_file_mode = 0600 # creation mode for log files,
# begin with 0 to use octal notation
#log_truncate_on_rotation = off # If on, an existing log file with the
# same name as the new log file will be
# truncated rather than appended to.
# But such truncation only occurs on
# time-driven rotation, not on restarts
# or size-driven rotation. Default is
# off, meaning append to existing files
# in all cases.
#log_rotation_age = 1d # Automatic rotation of logfiles will
# happen after that time. 0 disables.
#log_rotation_size = 10MB # Automatic rotation of logfiles will
# happen after that much log output.
# 0 disables.
# These are relevant when logging to syslog:
#syslog_facility = 'LOCAL0'
#syslog_ident = 'postgres'
#syslog_sequence_numbers = on
#syslog_split_messages = on
# This is only relevant when logging to eventlog (win32):
# (change requires restart)
#event_source = 'PostgreSQL'
# - When to Log -
#log_min_messages = warning # values in order of decreasing detail:
# debug5
# debug4
# debug3
# debug2
# debug1
# info
# notice
# warning
# error
# log
# fatal
# panic
#log_min_error_statement = error # values in order of decreasing detail:
# debug5
# debug4
# debug3
# debug2
# debug1
# info
# notice
# warning
# error
# log
# fatal
# panic (effectively off)
#log_min_duration_statement = -1 # -1 is disabled, 0 logs all statements
# and their durations, > 0 logs only
# statements running at least this number
# of milliseconds
# - What to Log -
#debug_print_parse = off
#debug_print_rewritten = off
#debug_print_plan = off
#debug_pretty_print = on
#log_checkpoints = off
#log_connections = off
#log_disconnections = off
#log_duration = off
#log_error_verbosity = default # terse, default, or verbose messages
#log_hostname = off
#log_line_prefix = '%m [%p] ' # special values:
# %a = application name
# %u = user name
# %d = database name
# %r = remote host and port
# %h = remote host
# %p = process ID
# %t = timestamp without milliseconds
# %m = timestamp with milliseconds
# %n = timestamp with milliseconds (as a Unix epoch)
# %i = command tag
# %e = SQL state
# %c = session ID
# %l = session line number
# %s = session start timestamp
# %v = virtual transaction ID
# %x = transaction ID (0 if none)
# %q = stop here in non-session
# processes
# %% = '%'
# e.g. '<%u%%%d> '
#log_lock_waits = off # log lock waits >= deadlock_timeout
#log_statement = 'none' # none, ddl, mod, all
#log_replication_commands = off
#log_temp_files = -1 # log temporary files equal or larger
# than the specified size in kilobytes;
# -1 disables, 0 logs all temp files
log_timezone = 'Europe/Chisinau'
# - Process Title -
#cluster_name = '' # added to process titles if nonempty
# (change requires restart)
#update_process_title = on
#------------------------------------------------------------------------------
# RUNTIME STATISTICS
#------------------------------------------------------------------------------
# - Query/Index Statistics Collector -
#track_activities = on
#track_counts = on
#track_io_timing = off
#track_functions = none # none, pl, all
#track_activity_query_size = 1024 # (change requires restart)
#stats_temp_directory = 'pg_stat_tmp'
# - Statistics Monitoring -
#log_parser_stats = off
#log_planner_stats = off
#log_executor_stats = off
#log_statement_stats = off
#------------------------------------------------------------------------------
# AUTOVACUUM PARAMETERS
#------------------------------------------------------------------------------
#autovacuum = on # Enable autovacuum subprocess? 'on'
# requires track_counts to also be on.
#log_autovacuum_min_duration = -1 # -1 disables, 0 logs all actions and
# their durations, > 0 logs only
# actions running at least this number
# of milliseconds.
#autovacuum_max_workers = 3 # max number of autovacuum subprocesses
# (change requires restart)
#autovacuum_naptime = 1min # time between autovacuum runs
#autovacuum_vacuum_threshold = 50 # min number of row updates before
# vacuum
#autovacuum_analyze_threshold = 50 # min number of row updates before
# analyze
#autovacuum_vacuum_scale_factor = 0.2 # fraction of table size before vacuum
#autovacuum_analyze_scale_factor = 0.1 # fraction of table size before analyze
#autovacuum_freeze_max_age = 200000000 # maximum XID age before forced vacuum
# (change requires restart)
#autovacuum_multixact_freeze_max_age = 400000000 # maximum multixact age
# before forced vacuum
# (change requires restart)
#autovacuum_vacuum_cost_delay = 20ms # default vacuum cost delay for
# autovacuum, in milliseconds;
# -1 means use vacuum_cost_delay
#autovacuum_vacuum_cost_limit = -1 # default vacuum cost limit for
# autovacuum, -1 means use
# vacuum_cost_limit
#------------------------------------------------------------------------------
# CLIENT CONNECTION DEFAULTS
#------------------------------------------------------------------------------
# - Statement Behavior -
#client_min_messages = notice # values in order of decreasing detail:
# debug5
# debug4
# debug3
# debug2
# debug1
# log
# notice
# warning
# error
#search_path = '"$user", public' # schema names
#default_tablespace = '' # a tablespace name, '' uses the default
#temp_tablespaces = '' # a list of tablespace names, '' uses
# only default tablespace
#check_function_bodies = on
#default_transaction_isolation = 'read committed'
#default_transaction_read_only = off
#default_transaction_deferrable = off
#session_replication_role = 'origin'
#statement_timeout = 0 # in milliseconds, 0 is disabled
#lock_timeout = 0 # in milliseconds, 0 is disabled
#idle_in_transaction_session_timeout = 0 # in milliseconds, 0 is disabled
#vacuum_freeze_min_age = 50000000
#vacuum_freeze_table_age = 150000000
#vacuum_multixact_freeze_min_age = 5000000
#vacuum_multixact_freeze_table_age = 150000000
#bytea_output = 'hex' # hex, escape
#xmlbinary = 'base64'
#xmloption = 'content'
#gin_fuzzy_search_limit = 0
#gin_pending_list_limit = 4MB
# - Locale and Formatting -
datestyle = 'iso, mdy'
#intervalstyle = 'postgres'
timezone = 'Europe/Chisinau'
#timezone_abbreviations = 'Default' # Select the set of available time zone
# abbreviations. Currently, there are
# Default
# Australia (historical usage)
# India
# You can create your own file in
# share/timezonesets/.
#extra_float_digits = 0 # min -15, max 3
#client_encoding = sql_ascii # actually, defaults to database
# encoding
# These settings are initialized by initdb, but they can be changed.
lc_messages = 'en_US.utf8' # locale for system error message
# strings
lc_monetary = 'en_US.utf8' # locale for monetary formatting
lc_numeric = 'en_US.utf8' # locale for number formatting
lc_time = 'en_US.utf8' # locale for time formatting
# default configuration for text search
default_text_search_config = 'pg_catalog.english'
# - Other Defaults -
#dynamic_library_path = '$libdir'
#extension_destdir = '' # prepend path when loading extensions
# and shared objects (added by Debian)
#local_preload_libraries = ''
#session_preload_libraries = ''
#------------------------------------------------------------------------------
# LOCK MANAGEMENT
#------------------------------------------------------------------------------
#deadlock_timeout = 1s
#max_locks_per_transaction = 64 # min 10
# (change requires restart)
#max_pred_locks_per_transaction = 64 # min 10
# (change requires restart)
#max_pred_locks_per_relation = -2 # negative values mean
# (max_pred_locks_per_transaction
# / -max_pred_locks_per_relation) - 1
#max_pred_locks_per_page = 2 # min 0
#------------------------------------------------------------------------------
# VERSION/PLATFORM COMPATIBILITY
#------------------------------------------------------------------------------
# - Previous PostgreSQL Versions -
#array_nulls = on
#backslash_quote = safe_encoding # on, off, or safe_encoding
#default_with_oids = off
#escape_string_warning = on
#lo_compat_privileges = off
#operator_precedence_warning = off
#quote_all_identifiers = off
#standard_conforming_strings = on
#synchronize_seqscans = on
# - Other Platforms and Clients -
#transform_null_equals = off
#------------------------------------------------------------------------------
# ERROR HANDLING
#------------------------------------------------------------------------------
#exit_on_error = off # terminate session on any error?
#restart_after_crash = on # reinitialize after backend crash?
#data_sync_retry = off # retry or panic on failure to fsync
# data?
# (change requires restart)
#------------------------------------------------------------------------------
# CONFIG FILE INCLUDES
#------------------------------------------------------------------------------
# These options allow settings to be loaded from files other than the
# default postgresql.conf. Note that these are directives, not variable
# assignments, so they can usefully be given more than once.
#include_dir = '...' # include files ending in '.conf' from
# a directory, e.g., 'conf.d'
#include_if_exists = '...' # include file only if it exists
#include = '...' # include file
#------------------------------------------------------------------------------
# CUSTOMIZED OPTIONS
#------------------------------------------------------------------------------
# Add settings for extensions here

View File

@@ -0,0 +1,50 @@
services:
db:
image: postgres:10
container_name: postgres_prod_trade
restart: always
env_file: .env
environment:
- TZ=${TZ}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_DB=${POSTGRES_DB}
ports:
- "5432:5432"
volumes:
- ./pgdata:/var/lib/postgresql/data
# Read-only config mounts for security
- ./config/postgresql.conf:/etc/postgresql/postgresql.conf:ro
- ./config/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro
# Syncs container time with host system time
- /etc/localtime:/etc/localtime:ro
- /etc/timezone:/etc/timezone:ro
# Use configuration files from ./config instead of ./pgdata
command: ["postgres", "-c", "config_file=/etc/postgresql/postgresql.conf"]
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
interval: 10s
timeout: 5s
retries: 5
backup_cron:
image: prodrigestivill/postgres-backup-local:10
container_name: postgres_backup_service_trade
restart: always
env_file: .env
depends_on:
db:
condition: service_healthy
environment:
- TZ=${TZ}
- POSTGRES_HOST=db
- POSTGRES_DB=${POSTGRES_DB}
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
- SCHEDULE=${BACKUP_SCHEDULE}
- BACKUP_KEEP_DAYS=${BACKUP_RETENTION_DAYS}
- BACKUP_DIR=/backups
volumes:
- ./backups:/backups
- /etc/localtime:/etc/localtime:ro
- /etc/timezone:/etc/timezone:ro

View File

@@ -0,0 +1,163 @@
#!/bin/bash
# --- AUTOMATIC PATH SETTING ---
# This ensures the script always runs inside the folder where it lives
PARENT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$PARENT_DIR"
# --- .env LOADING ---
# This safely loads the variables from .env without touching other files
if [ -f "$PARENT_DIR/.env" ]; then
set -a
source "$PARENT_DIR/.env"
set +a
echo "[✔] Environment variables loaded."
else
echo "[!] No .env file found. Using defaults."
fi
# Container naming
DB_CONTAINER_NAME="postgres_prod_trade"
BACKUP_CONTAINER_NAME="postgres_backup_service_trade"
IMAGE_TAG="10"
# --- I. SETUP ---
setup_environment() {
echo "--- Phase 1: Environment Setup in $PARENT_DIR ---"
# 1. Create folders relative to script location
mkdir -p "$PARENT_DIR/config" "$PARENT_DIR/pgdata" "$PARENT_DIR/backups"
echo "[✔] Directories verified: config, pgdata, backups"
# 2. Extract default configs if they don't exist
if [ ! -f "$PARENT_DIR/config/postgresql.conf" ]; then
echo "[!] Configuration files are missing. Searching for templates..."
if [ "$PARENT_DIR/config_template/postgresql.conf" ] && [ "$PARENT_DIR/config_template/postgresql.conf" ]; then
read -p " config_template found, do you want to create template configuration from this files or from docker container? [y - config_template/n - docker]: " config_decision
if [ "$config_decision" == "y" ]; then
echo "[!] Copying custom templates from config_template/..."
cp "$PARENT_DIR/config_template/postgresql.conf" "$PARENT_DIR/config/postgresql.conf"
cp "$PARENT_DIR/config_template/pg_hba.conf" "$PARENT_DIR/config/pg_hba.conf"
echo "[✔] Config files copied."
elif [ "$config_decision" == "n" ]; then
echo "[!] Extracting default config templates..."
docker run --rm postgres:$IMAGE_TAG cat /usr/share/postgresql/$IMAGE_TAG/postgresql.conf.sample > "$PARENT_DIR/config/postgresql.conf"
docker run --rm postgres:$IMAGE_TAG cat /usr/share/postgresql/$IMAGE_TAG/pg_hba.conf.sample > "$PARENT_DIR/config/pg_hba.conf"
echo "[✔] Config files extracted."
read -p " Make sure to update the configuration files to match your needs. Press any key: "
else
echo "[✘] Invalid input! Please run the script again and choose 'y' or 'n'."
fi
else
echo "[!] Extracting default config templates..."
docker run --rm postgres:$IMAGE_TAG cat /usr/share/postgresql/$IMAGE_TAG/postgresql.conf.sample > "$PARENT_DIR/config/postgresql.conf"
docker run --rm postgres:$IMAGE_TAG cat /usr/share/postgresql/$IMAGE_TAG/pg_hba.conf.sample > "$PARENT_DIR/config/pg_hba.conf"
echo "[✔] Config files extracted."
read -p " Make sure to update the configuration files to match your needs. Press any key: "
fi
else
echo "[i] Config files already exist. Skipping extraction."
fi
# 3. Set permissions (Postgres UID 999)
echo "[!] Applying production permissions (sudo required)..."
sudo chown -R 999:999 "$PARENT_DIR/pgdata" "$PARENT_DIR/config" "$PARENT_DIR/backups"
echo "[✔] Permissions set."
}
# --- II. CONTAINER MANAGEMENT ---
deploy_containers() {
echo "--- Phase 2: Deploying Containers ---"
docker compose up -d
echo "[✔] Services started."
}
show_status() {
echo "--- Service Status ---"
docker compose ps
echo ""
echo "--- Resource Usage ---"
docker stats --no-stream $DB_CONTAINER_NAME $BACKUP_CONTAINER_NAME
}
# --- III. SCRIPTS / UTILS ---
run_backup() {
echo "--- Phase 3: Manual Backup Trigger ---"
docker exec $BACKUP_CONTAINER_NAME /backup.sh
echo "[✔] Backup completed. Check ./backups/"
}
run_restore() {
if [ -z "$1" ]; then
echo "[✘] Error: Filename required. Usage: ./manage_db.sh restore filename.sql.gz"
exit 1
fi
FILE_PATH="$PARENT_DIR/$1"
if [ ! -f "$FILE_PATH" ]; then
echo "[✘] Error: File $FILE_PATH not found!"
exit 1
fi
echo "⚠️ WARNING: Restoring to database: ${POSTGRES_DB}"
read -p "This will overwrite existing data. Confirm? (y/n): " confirm
if [ "$confirm" == "y" ]; then
echo "[!] Starting restore..."
if [[ "$1" == *.gz ]]; then
gunzip -c "$FILE_PATH" | docker exec -i $DB_CONTAINER_NAME psql -U $POSTGRES_USER -d $POSTGRES_DB
elif [[ "$2" == *.gz ]]; then
cat "$FILE_PATH" | docker exec -i $DB_CONTAINER_NAME psql -U $POSTGRES_USER -d $POSTGRES_DB
else
# Fallback for binary .dump files
docker exec -i $DB_CONTAINER_NAME pg_restore -U $POSTGRES_USER -d $POSTGRES_DB --clean --if-exists < "$FILE_PATH"
fi
echo "[✔] Restore successful."
else
echo "[i] Restore aborted."
fi
}
# --- COMMAND LOGIC ---
case "$1" in
setup)
setup_environment
;;
run|start)
deploy_containers
;;
stop)
echo "[!] Stopping services..."
docker compose stop
;;
status)
show_status
;;
logs)
docker compose logs -f
;;
update)
echo "[!] Rebuilding and restarting services..."
docker compose up -d --remove-orphans
;;
enter)
echo "[!] Entering container terminal... (type 'exit' to leave)"
sudo docker exec -it $DB_CONTAINER_NAME bash
;;
psql)
echo "[!] Entering SQL prompt..."
# This automatically uses the DB and User from your .env
sudo docker exec -it $DB_CONTAINER_NAME psql -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-db}
;;
backup)
run_backup
;;
restore)
run_restore "$2"
;;
*)
echo "Usage: $0 {setup|run|stop|status|logs|update|enter|psql|backup|restore filename.sql.gz}"
exit 1
esac