# How to connect to PostgreSQL running in a docker container from outside?

To connect to PostgreSQL running in a Docker container from outside the container, you need to expose the PostgreSQL port and provide the necessary authentication credentials. Here are the steps:

1. When starting the PostgreSQL container, you need to expose the port that PostgreSQL is listening on. This can be done by specifying the `p` flag followed by the host port and container port mappings. For example:
    
    ```bash
    docker run -d -p 5432:5432 --name postgres postgres
    ```
    
    This will start a new PostgreSQL container with the port mapping of `5432:5432`, exposing PostgreSQL port 5432 to the host.
    
2. Once the container is running and the port is exposed, you can connect to PostgreSQL from outside the container using any PostgreSQL client such as `psql`. The syntax is as follows:
    
    ```bash
    psql -h <host> -p <port> -U <username> -d <database>
    ```
    
    Where `<host>` is the IP address or hostname of the host running the container, `<port>` is the host port that maps to the container port (5432 in our example), `<username>` is the PostgreSQL username, and `<database>` is the name of the PostgreSQL database.
    
    For example, if the host IP address is `192.168.0.100` and the PostgreSQL username is `postgres`, you would run:
    
    ```bash
    psql -h 192.168.0.100 -p 5432 -U postgres -d mydatabase
    ```
    
    This will connect to the PostgreSQL server running in the Docker container, using the specified database and authentication credentials.
    
    Note: By default, the `postgres` user does not have a password set. If you have set a password for the `postgres` user, you need to include the `-W` flag followed by the password when connecting to PostgreSQL. For example:
    
    ```bash
    psql -h 192.168.0.100 -p 5432 -U postgres -W -d mydatabase
    ```
    
    This will prompt you for the password before connecting to the PostgreSQL server.