Skip to content

Commit 1de0f5c

Browse files
authored
Allowing a container in Docker Desktop for Mac to talk to a PostgreSQL server on the host machine
1 parent 8b5c670 commit 1de0f5c

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Allowing a container in Docker Desktop for Mac to talk to a PostgreSQL server on the host machine
2+
3+
I like using [Postgres.app](https://postgresapp.com/) to run PostgreSQL on my macOS laptop. I use it for a bunch of different projects.
4+
5+
When I deploy applications to Fly.io I build them as Docker containers and inject the Fly PostgreSQL database details as a `DATABASE_URL` environment variable.
6+
7+
In order to test those containers on my laptop, I needed to figure out a way to set a `DATABASE_URL` that would point to the PostgreSQL I have running on my own laptop - so that I didn't need to spin up another PostgreSQL Docker container just for testing purposes.
8+
9+
## host.docker.internal
10+
11+
The first thing to know is that Docker for Desktop sets `host.docker.internal` as a magic hostname inside the container that refers back to the IP address of the host machine.
12+
13+
So ideally something like this should work:
14+
15+
docker run --env DATABASE_URL="postgres://docker:[email protected]:5432/pillarpointstewards" \
16+
-p 8080:8000 pillarpointstewards
17+
18+
I'm using `-p 8080:8000` here to set port 8080 on my laptop to forward to the Django application server running on port 8000 inside the container.
19+
20+
## Creating the account and granting permissions
21+
22+
To create that PostgreSQL account with username `docker` and password `docker-password` (but pick a better password than that) I used Postico to open a connection to my `postgres` database and ran the following:
23+
24+
create role docker login password 'docker-password';
25+
26+
Then I connected to my application database (in this case `pillarpointstewards`) and ran the following to grant permissions to that user:
27+
```sql
28+
GRANT ALL ON ALL TABLES IN SCHEMA "public" TO docker;
29+
```
30+
Having done this, the container run with the above `DATABASE_URL` environment variable was able to both connect to the server and run Django migrations too.

0 commit comments

Comments
 (0)