Interacting with the Docker container #
Should we find ourselves in need to interact with the container, we can use the docker exec command. For instance, we can start an interactive shell:
docker exec --interactive --tty demo-postgres /bin/bashThe container may only include the Bourne shell
/bin/shand not the Bourne Again shell/bin/bash.
You can now execute commands in the shell, such as ls -lha, ps xua, etc. The number of available commands and utilities depend on what was packaged into the image. For example, man ls or tree are not available, but grep and find are.
Connect to PostgreSQL using docker exec:
docker exec -it demo-postgres psql --username=demouser --dbname=demodbIn the the PostgreSQL interactive terminal, perform a few database operations:
\l -- List databases
CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(50));
INSERT INTO users (name) VALUES ('Alice'), ('Bob'), ('Charlie');
SELECT * FROM users ORDER BY id ASC;
\q -- Exit PostgreSQL interactive terminalWe instructed Docker to publish the internal port 5432 as 5432, so we can connect directly to the PostgreSQL database without the need to go through Docker:
psql --host=127.0.0.1 --port=5432 --username=demouser --dbname=demodbYou can install the PostgreSQL interactive terminal on Debian using the following command:
sudo apt-get install --yes postgresql-clientFinally, should we need to copy a file into the container, we would use the docker cp command. For instance, let’s say that we created a file named student.sql in our working directory with the following content:
CREATE TABLE IF NOT EXISTS student (
id SERIAL PRIMARY KEY,
name VARCHAR(50)
);
INSERT INTO student (id, name)
VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie')
ON CONFLICT (id) DO NOTHING;Once the container is up and running, we could copy the file into the container:
docker cp student.sql demo-postgres:/docker-entrypoint-initdb.d/student.sqlAnd we could instruct the PostgreSQL interactive terminal to execute the sentences in that file:
docker exec -it demo-postgres psql -U demouser -d demodb -f /docker-entrypoint-initdb.d/student.sql