Home > Mobile >  How to write a bash script that access to database inside docker then insert data?
How to write a bash script that access to database inside docker then insert data?

Time:05-30

Provided, I have to go through a route of

  1. Get into docker

  2. Get into postgreSQL database

  3. Create table

  4. Insert data

Which is very troublesome to do it frequently since I am testing. I want to write a bash script (.sh file) that do everything in 1 run.

Here are all my command line I need to run

docker exec -it <mycontainer> bash

psql -h localhost -p 5432 -U postgres

CREATE SCHEMA bank;

CREATE TABLE bank.holding (
    holding_id int,
    user_id int,
    holding_stock varchar(8),
    holding_quantity int,
    datetime_created timestamp,
    datetime_updated timestamp,
    primary key(holding_id)
);

insert into bank.holding values (102100, 2, 'VFIAX', 10, now(), now());

CodePudding user response:

Firstly, it will assist you on automating the procedure if you expose your container port

docker container run ... -p 5432:5432 ...

The above procedure will enable you to access the container port, by directly accessing your localhost:5432

Next run

psql -h localhost -p 5432 -U postgres -f bash_automation_script.txt

bash_automation_script.txt

CREATE SCHEMA bank;

CREATE TABLE bank.holding (
    holding_id int,
    user_id int,
    holding_stock varchar(8),
    holding_quantity int,
    datetime_created timestamp,
    datetime_updated timestamp,
    primary key(holding_id)
);

insert into bank.holding values (102100, 2, 'VFIAX', 10, now(), now());
  • Related