Search code examples
postgresqlubuntulocale

Set the locale of the PostgreSQL cluster when installing on Ubuntu


When installing PostgreSQL from apt on Ubuntu, the command initdb to initialize the cluster is done automatically, and the locale is set from the enviroment.

I like to have my system in en_US.UTF8, but initialize the cluster in a different locale.

For that I've tried to set the environment variable locally for apt

LOCALE=es_ES.UTF-8 LC_MESSAGES=C apt install postgresql-15

but it's not working. apt output shows:

/usr/lib/postgresql/15/bin/initdb -D /var/lib/postgresql/15/main --auth-local peer --auth-host scram-sha-256 --no-instructions

The database cluster will be initialized with locale "en_US.utf8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

For completion a simplified version of my provision script looks like this:

MY_LOCALE="es_ES.UTF-8"

# Allow the system to use $MY_LOCALE
sed -i "s/^# ${MY_LOCALE} UTF-8/${MY_LOCALE} UTF-8/" /etc/locale.gen
locale-gen

# Uncomment these lines if $MY_LOCALE must be the default
# update-locale --reset LANG="${MY_LOCALE}" LC_CTYPE="${MY_LOCALE}"
# export LANG="${MY_LOCALE}"
# export LC_TYPE="${MY_LOCALE}"

# Set the locale locally to apt command
LOCALE="${MY_LOCALE}" LC_MESSAGES=C apt install postgresql-15

Is there any way to pass locale variables to apt/initdb on installation?

Update.

As the question is closed and no answers can be added I edit to explain my actual workaround:

MY_LOCALE="es_ES.UTF-8"

# Allow the system to use $MY_LOCALE
sed -i "s/^# ${MY_LOCALE} UTF-8/${MY_LOCALE} UTF-8/" /etc/locale.gen
locale-gen

# Uncomment these lines if $MY_LOCALE must be the default
# update-locale --reset LANG="${MY_LOCALE}" LC_CTYPE="${MY_LOCALE}"
# export LANG="${MY_LOCALE}"
# export LC_TYPE="${MY_LOCALE}"

# Backup default enviroment variables
BCK_LANG="${LANG}"
BCK_LC_CTYPE="${LC_CTYPE}"
BCK_LC_MESSAGES="${LC_MESSAGES}"

# Set the desired locale for PostgreSQL as default for the system
update-locale --reset LANG="${MY_LOCALE}" LC_CTYPE="${MY_LOCALE}" LC_MESSAGES=C

# Install PostgreSQL
apt install postgresql-15

# Restore default locale
update-locale --reset LANG="${BCK_LANG}" LC_CTYPE="${BCK_LC_CTYPE}" LC_MESSAGES="${BCK_LC_MESSAGES}"

unset BCK_LANG
unset BCK_LC_CTYPE
unset BCK_LC_MESSAGES

Solution

  • I don't think so.

    The behavior of the Ubuntu packages has always annoyed me. Do what I do: drop the cluster that the packages create automatically and create it again with the configuration you want.