Download
docker pull postgres
Create
Option 1 – docker run
docker run -d \
--name postgres-itsmetommy \
-e POSTGRES_PASSWORD=12345 \
-p 5432:5432 \
postgres
Option 2 – docker-compose
cat <<EOF > docker-compose.yml
version: '3'
services:
postgres:
image: postgres
environment:
POSTGRES_PASSWORD: "12345"
ports:
- "5432:5432"
container_name: postgres-itsmetommy
EOF
Create.
docker-compose up -d
Logs.
docker-compose logs -f
Test connection
nc -zv localhost 5432
Example
nc -zv localhost 5432
Connection to localhost port 5432 [tcp/postgresql] succeeded!
Connect
The password for this setup is 12345.
docker exec -it [CONTAINER_NAME] psql -U [USER]
Example
docker exec -it postgres-itsmetommy psql -U postgres
You can also use psql (brew install postgresql on MacOS)
Note: The default user and database name is postgres.
psql -h localhost -p 5432 -d [DATABASE] -U [USER] --password
Example
psql -h localhost -p 5432 -d postgres -U postgres --password
Setup
Create a user and database.
CREATE USER tommy WITH PASSWORD '12345';
CREATE DATABASE itsmetommy;
GRANT ALL PRIVILEGES ON DATABASE itsmetommy to tommy;
Connect to the database.
\c itsmetommy
Create users table.
CREATE TABLE users (
userid SERIAL PRIMARY KEY,
name TEXT,
age INT,
location TEXT
);
Verify.
# view tables
\d
List of relations
Schema | Name | Type | Owner
--------+------------------+----------+----------
public | users | table | postgres
public | users_userid_seq | sequence | postgres
(2 rows)
Clean up
Option 1 – If you used docker run
docker stop postgres-itsmetommy && docker rm postgres-itsmetommy
Option 2 – If you used docker-compose
docker-compose down