Advanced SQL with PostgreSQL / Readiness and an owned local lab

Connect to your course-owned database

Lesson 2 of 51. Open to read. No account needed.

Before changing data, establish which server, database and role you control. The name asql_lab alone is insufficient: another server could have a database with that name. This lesson creates a new local container and dedicated storage, then checks the connection without loading the course tables.

Complete the readiness check first. This is the reference macOS ARM64 → Linux ARM64 container route, using Bash or zsh. It uses your own computer, not a cloud account. Internet access is needed to obtain the tools/image; the subsequent SQL runs locally. Plan for the course's 8 GB host-RAM, two available cores and 5 GB free-disk recommendation; those are planning allowances, not measured minimums for every future task. This container is capped at 1 GB memory and two CPUs.

The boundary you are creating

The host workspace controls a dedicated local PostgreSQL container. The container's psql uses a local socket; a separate loopback TCP port reaches server port 5432. A dedicated volume stores data, and a local password file is mounted read-only.

The solid control arrow means the supplied helper asks your selected local Docker engine to operate this one Compose project. Inside its container, psql is the SQL client and PostgreSQL is the server. They have separate version checks even though the same image supplies both. The dashed TCP arrow shows the optional host endpoint; the commands here use the container's local socket. The volume persists data when the container stops. The password file supplies bootstrap initialization input; it is not a database backup or ownership marker.

asql_bootstrap is the image-created setup superuser. Use it only for this owned bootstrap and later explicit setup/reset instructions. The next lesson creates a restricted asql_student role for routine queries. Do not interpret a setup superuser's successful read as evidence that another role has permission.

Obtain a local engine, not a remote target

If Docker and Compose already work locally, keep them and run the checks below. Otherwise, on the reference Mac, use the official Docker Desktop installation guide: choose the Apple-silicon installer, open its disk image, install the application, start it and complete its prompts under terms that apply to your environment. Wait until its engine is running. Do not install/update a shared machine's runtime without its administrator. These exercises need no managed database or paid database GUI.

In your host terminal, run:

docker version
docker compose version
docker context show

docker version should report both client and server. A client version alone does not show a usable engine. Compose is the command that reads the small service definition supplied below. A context identifies the engine the client contacts; a working remote context is not this course's local lab.

Set the context explicitly. desktop-linux is the tested Docker Desktop name; if your approved local runtime uses another name, replace only that value and inspect its endpoint before proceeding.

asql_context=desktop-linux
docker --context "$asql_context" context inspect "$asql_context" \
  --format '{{.Endpoints.docker.Host}}'

For the tested Mac this is a local unix:// socket path. Stop if it points to an employer server, remote host or engine you do not own. Do not switch or reconfigure another context. Every supplied helper call uses this explicit selection rather than changing your default context.

Create a fresh workspace and record its identity

The following host-terminal block chooses a new lab ID from the date/time and the shell's random value. Names are still checked before resource creation. mkdir has no -p: an existing directory is an error, not permission to reuse it. Port 55432 is an example configurable host port; choose another if it is occupied.

asql_run="asql-$(date +%Y%m%d%H%M%S)-$RANDOM"
asql_port=55432
asql_dir="$HOME/$asql_run"
umask 077
mkdir "$asql_dir" &&
  cd "$asql_dir" &&
  printf '%s\n' "$asql_run" "$asql_port" "$asql_context" > connection.txt &&
  pwd

The && chain runs each step only if its predecessor succeeds, preventing a failed mkdir/cd from writing the record into another directory. Stop if any step fails. umask 077 makes newly created files private to your user; it does not change permissions on existing files. connection.txt holds three non-secret lines: lab ID, port and context. Keep the printed directory location so you can return to the same lab rather than accidentally create a new one.

Using your text editor, create bootstrap-password.txt in this new directory. Put one newly chosen, throwaway local password on its first line. Do not reuse a real account password, put it in the Compose text, or commit this file. Save it as UTF-8 plain text. Then restrict its permissions:

chmod 600 bootstrap-password.txt

The file is local secret input, not an external account. Do not print it in screenshots or diagnostic logs. It must remain available while this service uses its secret mount.

Supply the complete local definition

Save the following complete file as compose.yaml in the same directory:

name: ${ASQL_RUN_ID:?Set the lab ID through session.sh}
services:
  db:
    init: true
    image: postgres:18.6@sha256:edb0c08dc33befd0262ab3b5cf1c4f3f8cfd8b09e88c05b45adee29d6761ddb6
    restart: "no"
    cpus: 2.0
    mem_limit: 1g
    shm_size: 128m
    environment:
      POSTGRES_USER: asql_bootstrap
      POSTGRES_DB: asql_lab
      POSTGRES_PASSWORD_FILE: /run/secrets/bootstrap_password
    secrets:
      - bootstrap_password
    ports:
      - "127.0.0.1:${ASQL_PORT:?Set the lab port through session.sh}:5432"
    volumes:
      - data:/var/lib/postgresql
    labels:
      com.vectametric.course: advanced-sql
      com.vectametric.lab-id: ${ASQL_RUN_ID:?}
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "asql_bootstrap", "-d", "asql_lab"]
      interval: 10s
      timeout: 5s
      retries: 30
volumes:
  data:
    name: ${ASQL_RUN_ID:?}-data
    labels:
      com.vectametric.course: advanced-sql
      com.vectametric.lab-id: ${ASQL_RUN_ID:?}
secrets:
  bootstrap_password:
    file: ./bootstrap-password.txt

The service enables Docker's init process from the first setup. It forwards signals and reaps orphan processes so PostgreSQL need not act as their supervisor. The direct CMD healthcheck starts pg_isready without an extra shell, polling every 10 seconds with a 5-second probe timeout. These process/readiness settings do not change SQL lock or statement limits or prove transaction correctness.

The image reference pins the observed PostgreSQL 18.6 artifact, rather than silently taking a new latest image. The resource limits bound this lab only. The port mapping binds your chosen host port to 127.0.0.1, forwarding it to server port 5432. It does not expose the server on every host network interface.

The named volume has your lab ID and labels. PostgreSQL 18's image uses mount target /var/lib/postgresql and PGDATA /var/lib/postgresql/18/docker; an older major's /var/lib/postgresql/data recipe is not this setup. Initialization variables act on empty data storage. Editing them or restarting does not reset an already initialized database.

Compose grants this service the file-backed secret at /run/secrets/bootstrap_password; this is a local mounted file, not a cloud secret vault. pg_isready is a readiness probe, not a fixture-correctness, authorization or password-authentication test. The finite wait below provides a failure boundary rather than leaving you waiting indefinitely.

Save this complete helper as session.sh beside the other files:

# Source this locally authored file from your lab directory in Bash or zsh.
asql_dir="$PWD"
unset -f asql 2>/dev/null
if [ ! -f "$asql_dir/connection.txt" ]; then
  printf '%s\n' 'Stop: connection.txt is missing from this directory.' >&2
  return 1
fi
if ! {
  IFS= read -r asql_run
  IFS= read -r asql_port
  IFS= read -r asql_context
} < "$asql_dir/connection.txt"; then
  printf '%s\n' 'Stop: connection.txt must contain three complete lines.' >&2
  return 1
fi
asql_endpoint=$(docker --context "$asql_context" context inspect "$asql_context" \
  --format '{{.Endpoints.docker.Host}}') || return 1
case "$asql_endpoint" in
  unix://*) ;;
  *) printf '%s\n' 'Stop: this route requires an owned local Unix-socket context.' >&2; return 1 ;;
esac
asql() {
  ASQL_RUN_ID="$asql_run" ASQL_PORT="$asql_port" \
    docker --context "$asql_context" compose --project-name "$asql_run" \
    --project-directory "$asql_dir" -f "$asql_dir/compose.yaml" "$@"
}

This is a shell helper, not SQL. read -r loads the three lines without treating backslashes as escapes. IFS= preserves their text. The asql function supplies the recorded project, directory and context each time; "$@" forwards your arguments without splitting a quoted argument. The two uppercase variables are set only for that command, preventing an unrelated exported value from choosing this lab's volume or port. unset -f clears a stale copy of this course helper before loading new inputs. The read check refuses an incomplete three-line record; return 1 stops loading a missing or incomplete session. The endpoint case check also refuses a non-local context before the wrapper is made available. This reference helper accepts local Unix-socket engines; other platform routes need qualification.

Load only this locally authored file, from the directory where you created it:

. ./session.sh
printf 'Lab: %s\nPort: %s\nContext: %s\n' "$asql_run" "$asql_port" "$asql_context"

The leading dot executes the helper in your current shell, so the function remains available. Inspect the file before sourcing it; do not source untrusted downloads. In a new terminal, return to this same directory and repeat these two commands.

Prove fresh state, start, then inspect

Before first creation, inspect the exact proposed names:

docker --context "$asql_context" ps -a \
  --filter "label=com.docker.compose.project=$asql_run" --format '{{.ID}}'
docker --context "$asql_context" volume inspect "$asql_run-data"
docker --context "$asql_context" network inspect "${asql_run}_default"

The container list must be empty, and both inspect commands should report not found. Those inspect failures are expected evidence of absence. If a resource exists, stop and choose a genuinely fresh lab ID/workspace; do not delete an existing resource to make the test pass.

From your new lab directory:

asql config --quiet
asql up -d --wait --wait-timeout 90 db
asql ps

The first command checks the definition without printing the secret. The second may download the pinned image and creates this project's network, volume and database container. -d leaves it running in the background; --wait waits for health, bounded by 90 seconds. No cloud resource is created. A successful start does not yet establish the SQL target.

Before SQL on a fresh empty volume, inspect this owned service's logs:

asql logs --tail 80 db

The image can briefly run an initialization server before its final server starts. A healthy probe during that phase is not enough. Require the init-complete message followed later by the final server's ready message, then perform the identity checks below. If initialization is still running, stop before bootstrap and inspect again; do not reset storage or treat a temporary shutdown as a completed fixture load. A restart of an already initialized volume does not repeat initialization, so its init-complete message need not appear anew: bounded startup and current identity/ fixture checks establish readiness. Changing initialization variables is no reset.

Inspect the running container and its volume:

docker --context "$asql_context" inspect "$(asql ps -q db)" \
  --format '{{index .Config.Labels "com.vectametric.lab-id"}} {{json .HostConfig.PortBindings}}'
docker --context "$asql_context" volume inspect "$asql_run-data" \
  --format '{{index .Labels "com.vectametric.lab-id"}}'

Both label values must match your recorded lab ID. The host binding must show 127.0.0.1 and your chosen port. If the container query returns no ID or anything differs, inspect your session values and stop before SQL writes. These checks link the connection to the newly created resources rather than to a familiar name.

Inspect the SQL connection

First check the client supplied inside the container:

asql exec -T db psql --version
asql exec -T db psql -X -v ON_ERROR_STOP=1 -U asql_bootstrap -d asql_lab

exec starts a client in the running service; -T omits a pseudo-terminal. The remaining options belong to psql: -X ignores local psql startup files, -v ON_ERROR_STOP=1 stops processing on an SQL error, -U chooses the login role and -d names the database. Stop-on-error is not automatic rollback of earlier statements; the fixture lesson explains that boundary.

At the SQL input, enter this complete read-only inspection:

SHOW server_version;
SHOW data_directory;
SELECT current_database(), session_user, current_user;
SELECT table_schema, table_name
FROM information_schema.tables
WHERE table_schema <> 'pg_catalog'
  AND table_schema <> 'information_schema';

SHOW displays a server setting. session_user identifies the session login; current_user is the current execution role. They match here, but later role changes can make them differ. The last query lists visible non-system tables and views; the setup superuser should see no application table in this newly initialized lab. These identifiers describe the connection; the earlier engine, labels and fresh-storage checks establish the ownership context.

Illustrative reference observations:

client: PostgreSQL 18.6
server: 18.6 (Debian packaging suffix may be shown)
data directory: /var/lib/postgresql/18/docker
database: asql_lab
session user: asql_bootstrap
execution role: asql_bootstrap
non-system table/view rows: 0

Your generated lab ID, host port and container ID vary. Check actual values; do not paste expected output as evidence. Exit the client with \q on a line by itself. With the non-TTY client, prompts/formatting may differ from a usual terminal; the SQL and exit command are the same.

The image's in-container Unix socket uses trusted local authentication. This setup connection therefore does not prove password authentication over TCP or application/tenant isolation. The mapped host port is a different route. Do not change host authentication to trust to repair a connection failure.

A successful connection can still be the wrong target

After exiting, try this read-only negative case from the host terminal:

asql exec -T db psql -X -v ON_ERROR_STOP=1 -U asql_bootstrap -d postgres \
  -c 'SELECT current_database(), current_user;'

This connects to the default postgres database in your same new container. Predict why it is unsuitable for the course fixture despite a successful exit. Then restore the explicit -d asql_lab target and repeat the identity check. Do not run any CREATE, reset or write while the database observation differs.

Hint 1: A database is one logical target within the server.

Hint 2: Compare observed identity with the intended contract, not only with the process exit code.

Answer and reasoning

The observed database is postgres, not asql_lab. The client reached a server successfully, but that does not authorize placing the course fixture there. Use the explicit course database, recheck both role and target, and preserve the default database. Before the first course marker exists, fresh owned resources and empty bootstrap state supply the evidence. After fixture initialization, the next lesson also requires its protected marker before writes or resets.

Interruption, recovery and owned cleanup

ObservationSafe next step
Command not found or no server sectionFinish the local tool installation/startup; do not point at a remote daemon to bypass it.
Host port already allocatedInspect only your new failed project, choose a free port in connection.txt, reload session.sh and retry. Do not kill the existing listener.
Wait timed outInspect asql ps and asql logs --tail 50 db; redact secrets if sharing logs. A restart does not repair a partial database initialization.
Wrong labels, context, database or roleStop before writes. Return to the correct owned workspace and explicit target.
New shell has no asql functionReturn to the same lab folder and source your inspected session.sh; do not generate a new lab ID automatically.

To pause an identified lab while keeping its data, run asql stop. Resume the same project with the bounded asql up command, then repeat identity checks. If continuing immediately, keep it running for the fixture lesson.

To discard this lab completely, first repeat the container/volume label and context checks above and confirm the project matches your recorded new lab. Then, only from that checked session, run:

asql down --volumes
docker --context "$asql_context" volume inspect "$asql_run-data"

This removes this Compose project's container/network and dedicated data volume; the inspect command must now report not found. The downloaded image may remain in the shared cache. Do not use a broad prune. Remove the password and local workspace only after confirming they belong to this discarded lab; keep them for a lab you intend to resume. Do not delete another project's volume or files.

If you need a native PostgreSQL route

Do not use an employer database as the alternative. A native route needs a separate owned PostgreSQL 18 instance/database, matching psql, setup identity and the same marker/fixture checks. Native installation and AMD64/WSL2 routes are not qualified by this reference walkthrough. If you cannot use this local container route, continue reading, and arrange an owned native environment with its administrator before executing later tasks. No paid hosted substitute is required or assumed. A native connection would use its explicit local host/port/role/database and its actual authentication method; container exec commands are not native-host commands.

References

46 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 149 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy