How do I create a postgresql container only to be accessed by ssh port 22

I need to run a container with postgresql, and set it up to only accepts requests by ssh.

What do you mean by “requests by ssh”? Do you want to allow the access to the database only to people who have SSH access to the server on which the container is running? If you do, you can forward a local port on you server to the container (docker run -p 127.0.0.2:5432:5432 ...) and use SSH tunnel like this:

ssh -L 127.0.0.1:5432:127.0.0.2:5432 -N yourserver@yourhostname

Leave that terminal open and connect to the database using 127.0.0.1 as host on your client machine. I have never used SSH tunnel for Postgres, but I always do it for MySQL. Some database manager GUI also have built-in support for SSH tunnel so you don’t need to do in in the terminal.

Note: You could use 127.0.0.1 where I used 127.0.0.2. I just wanted to show that you don’t need to use the same.