Home > Net >  with bash, is it possible to enter commands inside a docker container
with bash, is it possible to enter commands inside a docker container

Time:08-08

i'm trying to see if i can run commands after "entering" into a container:


#!/bin/sh

# 1 - create a new user in the db for mautic

podman exec -it postal-mariadb mysql -h 127.0.0.1 -u root -p$1 <<EOF
CREATE DATABASE mauticdb;
        CREATE USER 'mautic' IDENTIFIED BY /'$1/';
        GRANT ALL PRIVILEGES ON mauticdb.* TO 'mautic';
        FLUSH PRIVILEGES;
        exit
EOF

this gives me an error: Error: container create failed (no logs from conmon): EOF

but im thinking maybe this is not a good use of HERE DOCS

something like this doesn't work either:

echo $1 | podman exec -it postal-mariadb mysql -h 127.0.0.1 -u root -p postal-server-1 -e 'select * from deliveries limit 10;'

CodePudding user response:

That's a fine (and common) use of here docs, although you probably want to drop the -t from your podman command line. If I have a mariadb container running:

podman run -d --name mariadb -e MARIADB_ROOT_PASSWORD=secret docker.io/mariadb:10

Then if I put your shell script into a file named createdb.sh, modified to look like this for my environment:

podman exec -i mariadb mysql -u root -p$1 <<EOF
CREATE DATABASE mauticdb;
        CREATE USER 'mautic' IDENTIFIED BY '$1';
        GRANT ALL PRIVILEGES ON mauticdb.* TO 'mautic';
        FLUSH PRIVILEGES;
EOF

I've made three changes:

  1. I've removed the -t from the podman exec command line, since we're passing input on stdin rather than starting an interactive terminal;
  2. I removed the unnecessary exit command (the interactive mysql shell will exit when it reaches end-of-file);
  3. I removed the weird forward slashes around your quotes (/'$1/' -> '$1').

I can run it like this:

sh createdb.sh secret

And it runs without errors. The database exists:

$ podman exec mariadb mysql -u root -psecret -e 'show databases'
Database
information_schema
mauticdb   <--- THERE IT IS
mysql
performance_schema
sys

And the user exists:

$ podman exec mariadb mysql -u root -psecret mysql -e 'select user from user where user="mautic"'
User
mautic

  • Related