title: docker container connect local postgresql
body: <p>I run python container, I want to connect localhost postegresql. And I try some method. But not work. Please talk me. How can I do ? Thanks. </p>
  
  <p>I have run postegresql on port 5432, create datatbase and grant user.</p>
  
  <p>run docker comand</p>
  
  <pre><code>docker run --name=python3 -v ${pwd}:/code -w /code python
  </code></pre>
  
  <p>python code</p>
  
  <pre><code>import psycopg2
  
  def main():
      #Define our connection string
      conn_string = "host='localhost' dbname='testDB' user='test' password='test'"
  
      # print the connection string we will use to connect
      print ("Connecting to database\n    -&gt;{}".format(conn_string))
  
      # get a connection, if a connect cannot be made an exception will be raised here
      conn = psycopg2.connect(conn_string)
  
      # conn.cursor will return a cursor object, you can use this cursor to perform queries
      cursor = conn.cursor()
      print ("Connected!\n")
  
  if __name__ == "__main__":
      main()
  </code></pre>
  
  <p>error message</p>
  
  <blockquote>
    <p>Is the server running on host "localhost" (::1) and accepting
                TCP/IP connections on port 5432?
        could not connect to server: Connection refused
                Is the server running on host "localhost" (127.0.0.1) and accepting
                TCP/IP connections on port 5432?</p>
  </blockquote>