惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

罗磊的独立博客
Forbes - Security
Forbes - Security
Blog — PlanetScale
Blog — PlanetScale
P
Proofpoint News Feed
Apple Machine Learning Research
Apple Machine Learning Research
Google DeepMind News
Google DeepMind News
MyScale Blog
MyScale Blog
GbyAI
GbyAI
B
Blog RSS Feed
S
SegmentFault 最新的问题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
小众软件
小众软件
The Last Watchdog
The Last Watchdog
W
WeLiveSecurity
Webroot Blog
Webroot Blog
S
Security @ Cisco Blogs
Hugging Face - Blog
Hugging Face - Blog
Microsoft Security Blog
Microsoft Security Blog
月光博客
月光博客
博客园 - 聂微东
F
Fortinet All Blogs
H
Hacker News: Front Page
A
About on SuperTechFans
Application and Cybersecurity Blog
Application and Cybersecurity Blog
C
Check Point Blog
V
V2EX
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Y
Y Combinator Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
N
News | PayPal Newsroom
Cisco Talos Blog
Cisco Talos Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The Cloudflare Blog
P
Privacy & Cybersecurity Law Blog
N
Netflix TechBlog - Medium
C
CXSECURITY Database RSS Feed - CXSecurity.com
Recorded Future
Recorded Future
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Google DeepMind News
Google DeepMind News
大猫的无限游戏
大猫的无限游戏
美团技术团队
Security Latest
Security Latest
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
I
InfoQ
Recent Announcements
Recent Announcements
The GitHub Blog
The GitHub Blog
Google Online Security Blog
Google Online Security Blog
T
The Exploit Database - CXSecurity.com

Martin Heinz's Blog

A Guide to Python's Weak References Using weakref Module Recent Docker BuildKit Features You're Missing Out On Modern Git Commands and Features You Should Be Using Everything You Can Do with Python's textwrap Module Monitoring Indoor Air Quality with Prometheus, Grafana and a CO2 Sensor Everything You Can Do with Python's bisect Module You Don't Need a Dedicated Cache Service - PostgreSQL as a Cache A Collection of Docker Images To Solve All Your Debugging Needs Weird Python "Features" That Might Catch You By Surprise Lessons Learned From Writing 100 Articles Debugging Crashes and Deadlocks in Python using PyStack Goodbye etcd, Hello PostgreSQL: Running Kubernetes with an SQL Database Remote Interactive Debugging of Python Applications Running in Kubernetes The Right Way to Run Shell Commands From Python Real Multithreading is Coming to Python - Learn How You Can Use It Now Python's Missing Batteries: Essential Libraries You're Missing Out On Kubernetes-Native Synthetic Monitoring with Kuberhealthy Make Your CLI Demos a Breeze with Zero Stress and Zero Mistakes Reduce - The Power of a Single Python Function Why I Will Never Use Alpine Linux Ever Again Cgroups - Deep Dive into Resource Management in Kubernetes Dictionary Dispatch Pattern in Python Boost Your Python Application Performance using Continuous Profiling Lazy Evaluation Using Recursive Python Generators Python Magic Methods You Haven't Heard About Getting Started with Mastodon API in Python Backup-and-Restore of Containers with Kubernetes Checkpointing API Getting Started with Google APIs in Python Python CLI Tricks That Don't Require Any Code Whatsoever All The Ways To Introspect Python Objects at Runtime What is Python's "self" Argument, Anyway? Python List Comprehensions Are More Powerful Than You Might Think You Should Be Using Python's Walrus Operator - Here's Why Recipes and Tricks for Effective Structural Pattern Matching in Python It's Time to Say Goodbye to These Obsolete Python Libraries Advanced Features of Kubernetes' Horizontal Pod Autoscaler Data and System Visualization Tools That Will Boost Your Productivity Stop Messing with Kubernetes Finalizers Automate All the Boring Kubernetes Operations with Python End-to-End Monitoring with Grafana Cloud with Minimal Effort Bitly | bit.ly/3JLmSgA Bitly | bit.ly/3uETfbi Bitly | bit.ly/3MI4Iz0 Bitly | bit.ly/3M30D82 Bitly | bit.ly/3oMJ6qR Bitly | bit.ly/3IRD7IK Bitly | bit.ly/3A3B69t Bitly | bit.ly/31lKCYA Bitly | bit.ly/30uviIM Bitly | bit.ly/3E1X2mw Bitly | bit.ly/3Dv7JxP Bitly | bit.ly/3GG1BEz Bitly | bit.ly/3lLavs4 Bitly | bit.ly/39TqP3m Bitly | bit.ly/3A5Mpx8 Bitly | bit.ly/3kGwPl4 Bitly | bit.ly/3iHtulU Bitly | bit.ly/3xGjtKS Bitly | bit.ly/3h8DZg0 Bitly | bit.ly/2RQn1dG Bitly | bit.ly/3p2B5wW The Easiest Way to Debug Kubernetes Workloads Bitly | bit.ly/2PHVudx Cloud Native CI/CD with Tekton - Building Custom Tasks Bitly | bit.ly/3dg3QR9 Bitly | bit.ly/3qHtSkZ Deep Dive into Docker Internals - Union Filesystem Bitly | bit.ly/3qlRAUN Bitly | bit.ly/3pCUJ26 Bitly | bit.ly/3ifZxYr Bitly | bit.ly/34ZhIMt Bitly | bit.ly/3qSO7h0 Bitly | bit.ly/3muGLOk Bitly | bit.ly/35xN79v Bitly | bit.ly/3mLGshK Bitly | bit.ly/2IvkGQl Bitly | bit.ly/2Sk1KFK Bitly | bit.ly/3iCNIL6 Bitly | bit.ly/3beQPpy Saving Your Linux Machine from Certain Death New Features in Python 3.9 You Should Know About Deploy Any Python Project to Kubernetes Analyzing Docker Image Security Recursive SQL Queries with PostgreSQL Automating Every Aspect of Your Python Project Tour of Python Itertools Implementing 2D Physics in Javascript Ultimate Setup for Your Next Python Project Making Python Programs Blazingly Fast Security and Cryptography Mistakes You Are Probably Doing All The Time Going Serverless with OpenFaaS and Golang - Building Optimized Templates Going Serverless with OpenFaaS and Golang - The Ultimate Setup and Workflow Setting Up Swagger Docs for Golang API Building RESTful APIs in Golang Pytest Features, That You Need in Your (Testing) Life Setting up GitHub Package Registry with Docker and Golang Ultimate Setup for Your Next Golang Project Python Tips and Trick, You Haven't Already Seen, Part 2. Getting The Most Out of Reading Books - Reading The "Professional Way" Python Tips and Trick, You Haven't Already Seen
Tricks for Postgres and Docker that will make your life easier
Martin · 2019-09-02 · via Martin Heinz's Blog

Nowadays, everybody is trying to run everything in container and I don't blame them, I do the same thing, because running applications, databases or other tools in Docker container is super nice and we all know why (isolation, easy setup, security...). However, sometimes debugging, accessing, or in general interacting with containers can be pretty annoying. This includes accessing, modifying or querying databases. So, as I used PostgreSQL extensively and have been running it inside containers for a while now, I - over time - made a list of few commands that can help immensely when doing simple and also not so simple operation with a database server.

Log Into PSQL

The most basic thing you will always need to do if you want to interact with your database server is to connect to the database itself (using PSQL):

docker exec -it <container_name> psql -U<user_name> -a <db_name>

So for Docker container called db, default user postgres and database name blog it would be

docker exec -it db psql -Upostgres -a blog

Running Command Against Database

It's nice that you can log in and then execute whatever commands you need, but it's often more convenient to do it in one go, especially if you want to run just a single command or query:

docker exec -it <container_name> psql -U<user_name> -a <db_name> -c '<command/query>'

So if we wanted to list all tables in database using same parameters as in previous example:

docker exec -it db psql -Upostgres -a blog -c '\l'

Here, \l lists all tables in current database, if you are not familiar with psql "backslash" commands, then I highly recommend this cheatsheet.

Apart from psql commands you can run any SQL query like so:

docker exec -it db psql -Upostgres -a blog -c 'SELECT * FROM posts;'

Backing up Your Data

From time to time I need to backup data or whole schema of the database, sometimes just as an "insurance policy" and sometimes so I can make changes recklessly and restore everything afterwards, so here how to do it:

docker exec -it <container_name> pg_dump -U<user_name> --column-inserts --data-only <db_name> > backup.sql

In this example, we are making use of pg_dump utility, which allows us to extract PostgreSQL databases. I'm using --column-inserts and --data-only flags to get only table rows, but quite often all that is needed is schema, for that you can use -s flag.

Execute whole SQL files

Sometimes you need to populate existing database with enough data for testing (please don't do this with production databases) or it's just easier to use data from file then to copy and paste them into command above.


docker cp ./data.sql <container_name>:/data.sql
docker exec -it <container_name> psql -U<user_name> -a <db_name> -f /data.sql

Here we first need to copy the file itself into the running container and then execute it using the -f flag.

Prepopulating Database on the Start

Previous example was good enough if you need to execute it from time to time, but it can become annoying if you have to do it every time you start the database. So, in case you decide that it's better to just populate the database on the start, then here is solution for that. It just requires little more work:

We will need following files:

  • Dockerfile - Dockerfile for your Postgres image
  • create_db.sh - Script that creates database, schema and populates it.
  • schema.sql - SQL file containing your database schema
  • data.sql - SQL file containing data used to populate your database
  • .env - File with environment variables, to make your life easier

First, the Dockerfile:


FROM postgres:11

# Custom initialization scripts
COPY ./create_db.sh /docker-entrypoint-initdb.d/20-create_db.sh
COPY schema.sql /schema.sql
COPY data.sql /data.sql

RUN chmod +x /docker-entrypoint-initdb.d/20-create_db.sh

This is very simple Dockerfile, all we need to do here is to copy our script and schema/data into the image so they can be on run start-up. You may be asking, There is no ENTRYPOINT or COMMAND, how do we run it on start-up? - the answer is, that base postgres image runs on start any scripts present in docker-entrypoint-initdb.d directory, so all we need to do is copy our script to this directory and PostgreSQL takes care of it.

But what is in the script (create_db.sh)?


#!/bin/bash
set -e

POSTGRES="psql --username ${POSTGRES_USER}"

echo "Creating database: ${DB_NAME}"

$POSTGRES <<EOSQL
CREATE DATABASE ${DB_NAME} OWNER ${POSTGRES_USER};
EOSQL

echo "Creating schema..."
psql -d ${DB_NAME} -a -U${POSTGRES_USER} -f /schema.sql

echo "Populating database..."
psql -d ${DB_NAME} -a  -U${POSTGRES_USER} -f /data.sql

Start-up script first logs into psql with specified username (POSTGRES_USER), then it creates your database (DB_NAME). Next it creates database schema using file we copied into the image and finally it populates the database with data. All the variables here are coming from the .env file mentioned before, which makes it very easy to change your database name or username at any time without modifying script itself.

For more complete example please see my repository here

What About docker-compose?

In my experience, most of the time I end up running database in conjunction with the application that is using it and the simplest way to do it is docker-compose. Usually I prefer to refer to the docker-compose service by service name, rather then container name which might or might not be the same thing. In case it isn't same, you can just following command:

docker exec -it $(docker-compose ps -q <db_service_name>) psql -U<user_name> -a <db_name>

Only real difference here from the previous examples is the docker-compose part, which looks up information of the specified service. The -q flag make it so, that only container IDs are displayed, which is all we need.

Conclusion

I hope at least some of these little hacks will make your life easier when dealing with Docker and PostgreSQL or maybe if you were avoiding Docker just because it might be little annoying when working with databases, then I hope you will give it a shot after reading this article. 🙂