Nrgyzer
Nrgyzer

Reputation: 1075

Pod in Kubernetes not removed when psql command finished

In Kubernetes, I want start a PostgreSQL pod, create database, user and grant all privileges to the database to the user. So I came up with the following command:

kubectl run somepod --rm -i --restart=Never --image postgres:alpine --tty -- psql "postgresql://postgres:somepass@localhost" -c "CREATE DATABASE testdb" -c "CREATE USER myUser WITH PASSWORD 'password'" -c "GRANT ALL PRIVILEGES ON DATABASE testdb TO myUser"

It already works, but unfortunately the pod isn't terminated after the command. In Kubernetes, the pod is still alive and it's status is "Succeeded". I already tried adding -c '\q' to the command line because I assumed that psql is still running, but it didn't helped. Any ideas how I can remove the pod after the command has been succeeded?

Upvotes: 1

Views: 514

Answers (1)

Ralle Mc Black
Ralle Mc Black

Reputation: 1203

You can try something like this:

kubectl run  test4 -i --tty --image=postgres --restart=Never --rm  --command -- echo "hello"
hello
pod "test4" deleted

In your example, you are just executing a command in a running container, where postgres is started already.

You need to overvrite the command which is executed when the container is started.

Executing your command: (the error comes only because i didnt install any postgres)

kubectl run test4 -i --tty --image=postgres --restart=Never --rm --command -- psql "postgresql://postgres:somepass@localhost" -c "CREATE DATABASE testdb" -c "CREATE USER myUser WITH PASSWORD 'password'" -c "GRANT ALL PRIVILEGES ON DATABASE testdb TO myUser"

This will work if your postgres on localhost has right credentials.

Or it will return like so, because connection couldnt be established:

kubectl run  test4 -i --tty --image=postgres --restart=Never --rm  --command -- psql "postgresql://postgres:somepass@localhost" -c "CREATE DATABASE testdb" -c "CREATE USER myUser WITH PASSWORD 'password'" -c "GRANT ALL PRIVILEGES ON DATABASE testdb TO myUser"
psql: error: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
        Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address
        Is the server running on that host and accepting TCP/IP connections?
pod "test4" deleted

But however the pod is beeing deleted.

Hint to not doing that always manually , you can put a initContainer in your deployment or execute a job. Both with same image and Command.

Upvotes: 2

Related Questions