2

I'm trying to automate initializing a postgresql data directory, with a user and a default database pre-created. I know I can do this by running postgresql backgrounded and using createdb and createuser commands, but I really want to avoid that as this is for a docker container and I just want postgres to be running in the foreground once done.

In MySQL I use --init-file /path/to/bootstrap.sql, which runs the statements in the file before the server accepts connections. You can also use --bootstrap, which temporarily spins up mysqld and runs statements from STDIN.

I can't find an equally straightforward way to do this in Postgres. I can see a --boot option to postgres, but when I try and use it I just get "invalid command line arguments", so I must be doing something wrong.

echo "CREATE USER bob WITH PASSWORD 'secure';" | postgres --boot postgres -D data
postgres: invalid command-line arguments
2
  • What does it mean "postgres to be running in the foreground"? Aug 2, 2014 at 16:28
  • I mean what happens when you run postgres -D /path/to/data/dir. It sits in the foreground, which is exactly what Docker containers need to do :)
    – d11wtq
    Aug 2, 2014 at 22:06

1 Answer 1

3

You probably want the single user mode: --single, as described in the documentation:

When invoked in single-user mode from the shell, the user can enter queries and the results will be printed to the screen, but in a form that is more useful for developers than end users. In the single-user mode, the session user will be set to the user with ID 1, and implicit superuser powers are granted to this user. This user does not actually have to exist, so the single-user mode can be used to manually recover from certain kinds of accidental damage to the system catalogs

Note that initdb has be run to initialize an empty data directory before creating databases or users. That would be the equivalent of mysql_install_db if you prefer to look at this from the MySQL analogy angle.

1
  • Ah, that does seem to do what I need, thanks! I somehow mis-interpreted that documentation as if it kept postgresql running in a very insecure mode, so I'd have to shut it down. If you cat a file into postgres in that mode, it does the right thing!
    – d11wtq
    Aug 2, 2014 at 22:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.