https://scrapbox.io/shimizukawa/127.0.0.1_%E3%81%A8_0.0.0.0_%E3%81%AE%E9%81%95%E3%81%84 https://stackoverflow.com/questions/23639085/django-change-default-runserver-port
I ran Django inside a Docker container and tried to access the server from the host PC.
Although I did Port foward, I could not access the server from the host machine only with the normal python manage.py runserver
command.
Django sets the IP address to 127.0.0.1
by default, but this is the IP address of the local loopback interface, which is the IP address created virtually inside the machine. Therefore, access 127.0.0.1 from outside the container. Even if you try, there is no such thing.
On the other hand, when you start the server with Rails etc., the IP address assigned by default (although it is not strictly an IP address), 0.0.0.0
binds (assigns) the port specified for all Internet interfaces. Will give you.
To do this bind, you can execute the command python manage.py runserver 0.0.0.0
, but it is troublesome to type the last 0.0.0.0 every time you start the server, so by default 127.0.0.1
I decided to use 0.0.0.0
instead
If you have Django installed in your local environment and you're running the server from there
/usr/local/lib/python3.8/site-packages/django/core/management/commands
Somewhere in runserver.py
in
Set default_addr
to 0.0.0.0
.
runserver.py
default_addr = '0.0.0.0'
Just save with this
https://github.com/kshuta/Django_2.0_Docker
This repository contains a Dockerfile created to use Django 2 on Docker and its accompanying files. If you find it awkward to read below, try creating a Django app by downloading or using the above repository as a template.
The IP address defaults to 0.0.0.0
.
Please read the contents of the Readme and Dockerfile carefully before using it.
It's only been a month since I used Docker, so I'm not sure if this is the right way to go. But It does the work so why not.
** Get runserver.py from somewhere. ** **
If you google django 2 source code
etc., the source code of django is on github, so
Go to the django / core / management / commands
directory, download runserver.py and bring the file into the directory where your Dockerfile is.
** Add COPY notation in Dockefile ** Since runserver.py should be placed in the Docker context (maybe the usage of Docker context is wrong) in the previous step, add the following notation in the Dockerfile
Dockerfile
WORKDIR /usr/local/lib/python3.8/site-packages/django/core/management/commands
COPY runserver.py /usr/local/lib/python3.8/site-packages/django/core/management/commands/
WORKDIR /
Change the last WORKDIR to your favorite directory. It doesn't have to be the worst.
You have now changed the default IP address to 0.0.0.0! Now try running python manage.py runserver
from the shell inside the container. If you access localhost: 8000
firmly from the host machine, you can see the page you created.
Recommended Posts