Connecting to Postgres

First, I am running postgres in a container.

More specifically, I am using docker compose, so here is the yaml file:

version: "3.9"

services:
  # Our Postgres database
  db: # The service will be named db.
    image: postgres # The postgres image will be used
    restart: always # Always try to restart if this stops running
    environment: # Provide environment variables
      POSTGRES_USER: baloo # POSTGRES_USER env var w/ value baloo
      POSTGRES_PASSWORD: junglebook
      POSTGRES_DB: lenslocked # Database name
    ports: # Expose ports so that apps not running via docker-compose can connect to them.
      - 5432:5432 # format here is "port on our machine":"port on container"

  # Adminer provides a nice little web UI to connect to databases
  adminer:
    image: adminer
    restart: always
    environment:
      ADMINER_DESIGN: dracula # Pick a theme - https://github.com/vrana/adminer/tree/master/designs
    ports:
      - 3333:8080

The image “adminer” is just a GUI to configure the database, if desired.

But, from CLI, it would be like this:

docker compose exec -it db psql -U baloo -d lenslocked
psql (15.2 (Debian 15.2-1.pgdg110+1))
Type "help" for help.

The previous command would get me into the container where I can interact with the database:

lenslocked=# CREATE TABLE users (
lenslocked(# id SERIAL PRIMARY KEY,
lenslocked(# email TEXT
lenslocked(# );
CREATE TABLE
lenslocked=#

```postgres
lenslocked=# SELECT * FROM users;
 id | email
----+-------
(0 rows)
lenslocked=# INSERT INTO users(email) VALUES ('alex1@test.com');
INSERT 0 1
lenslocked=#
lenslocked=#
lenslocked=#
lenslocked=# SELECT * FROM users;
 id |     email
----+----------------
  1 | alex1@test.com
(1 row)

lenslocked=# INSERT INTO users(email) VALUES ('alex2@test.com');
INSERT 0 1
lenslocked=#
lenslocked=#
lenslocked=# SELECT * FROM users;
 id |     email
----+----------------
  1 | alex1@test.com
  2 | alex2@test.com
(2 rows)

lenslocked=#

 Share!

 
comments powered by Disqus