7

I am using Django as my Web-Framework. As a database I use PostgresSQL. To start my Postgres Database and the Webserver I use Docker.

When I start the server and db with docker-compose up, everything works fine. The database loads properly into Django and I dont get any errors.

But when I run for example python3 manange.py makemigrations django throws an error:

could not translate host name "db" to address: Name or service not known

Where "db" is the name of my postgres database. This is even then when server and database are running on a different window. What I find very weird is that the Database is found when I start with docker.

How do I access commands like python3 manage.py [...]?

So for example I need to create a superuser and dont know where to create that because if I use the normal python3 manage.py createsuperuser I get the same error as above.

The console window from starting docker I also cannot use because there the Django Server runs and just displays the incoming http posts and requests.

1
  • here It may help. Commented Jul 9, 2021 at 8:46

2 Answers 2

8

You'll need to use docker-compose exec to run the management command within your app container.

docker-compose exec webservicenamehere python manage.py makemigrations

(Refer to docker-compose ps or your compose YAML for webservicenamehere.)

You're getting that db error because the hostname db is only a thing within the Docker network that Docker Compose gives you; your host machine is not aware of such a hostname (and the database isn't directly exposed to the host machine anyway unless you say it should be).

Sign up to request clarification or add additional context in comments.

4 Comments

I am sorry to bother you. But where exactly can I find my Webcontainer Name?
docker-compose ps
@AKX By default, webcontainernamehere != servicename. docker-compose exec expects service name.
I found it its just he same given in the docker-compose.yml as a heading
1

You can docker-compose run a new container matching a template in your docker-compose.yml file, but with a different command and other settings.

docker-compose run djangoapp \
  ./manage.py createsuperuser

This has two notable advantages over docker-compose exec. You can only use exec on a container that's running, but run creates a new container; if your application can't start until it runs its initial migrations, you need run. Some complex setups do things like set up environment variables in an entrypoint script, and exec will not see these, but run will.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.