
Ahmed
02.12.2017
19:09:13
Как я понял надо хост мускула указывать в джанге или как?


serbernar
02.12.2017
19:11:48
Как я понял надо хост мускула указывать в джанге или как?
Welcome to the Docker Community Forums!
This is a public forum for users to discuss questions and explore current design patterns and best practices about Docker and related projects in the Docker Ecosystem.
To participate, just log in with your Docker Hub account. Make sure to also review our Community Guidelines, Terms of Service, and Privacy Policy.
When posting issues or feedback, make sure to remove any sensitive information and please provide the following:
Issue type
OS Version/build
App version
Steps to reproduce
Single db instance with multiple apps
Open Source Projects Compose
4
/
9

chadwell
Oct 20
I have 2 applications that are separate codebases, and they each have their own database on the same db server instance.
I am trying to replicate this in docker, locally on my laptop. I want to be able to have both apps use the same database instance.
I would like
both apps to start in docker at the same time
both apps to be able to access the database on localhost
the database data is persisted
be able to view the data in the database using an IDE on localhost
So each of my apps has its own dockerfile and docker-compose file.
On app1, I start the docker instance of the app which is tied to the database. It all starts fine.
When I try to start app2, I get the following error:
ERROR: for app2_mssql_1 Cannot start service mssql: driver failed programming external connectivity on endpoint app2_mssql_1 (12d550c8f032ccdbe67e02445a0b87bff2b2306d03da1d14ad5369472a200620): Bind for 0.0.0.0:1433 failed: port is already allocated
How can i have them both running at the same time? BOTH apps need to be able to access each others database tables!
Here is the docker-compose.yml files
app1:
version: "3" services: web: build: context: . args: volumes: - .:/app ports: - "3000:3000" depends_on: - mssql mssql: image: 'microsoft/mssql-server-linux' ports: - '1433:1433' environment: - ACCEPT_EULA=Y - SA_PASSWORD=SqlServer1234! volumes: - app1_docker_db:/var/lib/mssql/data volumes: app1_docker_db:
and here is app2:
version: "3" services: web: build: context: . args: volumes: - .:/app ports: - "3000:3000" depends_on: - mssql mssql: image: 'microsoft/mssql-server-linux' ports: - '1433:1433' environment: - ACCEPT_EULA=Y - SA_PASSWORD=SqlServer1234! volumes: - app2_docker_db:/var/lib/mssql/data volumes: app2_docker_db:
Should I be using the same volume in each docker-compose file? I guess the problem is in each app i am spinning up 2 different db instances, when in reality I guess i just want one, and it be used by all my apps?
created
Oct 20
last reply
Oct 23
8
replies

dmazeDavid Maze
Oct 20
 chadwell:
I have 2 applications that are separate codebases, and they each have their own database on the same db server instance.
I am trying to replicate this in docker, locally on my laptop. I want to be able to have both apps use the same database instance.
Start the database (I’ll claim MySQL, but this will work for anything) on the host. You can start it in a Docker container, if you’d prefer:
docker run -p 3306:3306 --name mysql -d mysql:5.6
This is not part of either application (it’s shared) so it doesn’t go in either application’s docker-compose.yml file.
Note your host’s IP address (on native Linux often 172.17.0.1 will work; on Docker Toolbox VMs often 192.168.99.1 will work), then configure the individual containers to talk to the database on that IP address, on port 3306, with whatever credentials you’ve configured, in the same way you’d configure it to talk to the external database.
You will never be able to access the database as “localhost” (and that’s normal).2

chadwell
Oct 20
Thanks for answering.
So this makes me think about the point of all this. So I should keep my database outside of my apps.
I guess this makes sense for local development. Developers can spin up the db and have it persisted on their workstation.
But how about deployment? If I were to deploy the apps to the cloud, using docker containers, how would the database work?
Would it be separate?
Как я понял надо хост мускула указывать в джанге или как?
What’s the standard or best approach?
Thanks

junius
Oct 22
yes, it is better to separate the database from the apps. One option is to create the apps and database to the same overlay network. You could create a new overlay network or use docker ingress overlay network. for example,
create an overlay network, docker network create -d overlay mynet.
create the database service, docker service create --name mydb --network mynet --replicas 1 dbimage.
create the app service, docker service create --name app1 --network mynet --replicas 1 myapp1. myapp1 could talk with db by the dns name mydb.
For DB, you would need to consider where data is stored, as container could move from one node to another. Could refer to question How does Docker Swarm handle database (PostgreSQL) replication?
Всё верно, нужно сетку между контейнерами пробросить

Google

Ahmed
02.12.2017
19:21:48

Sergey
02.12.2017
20:57:04

Kirill
02.12.2017
22:13:16
Почему оно ругается?
работает, но ругается)

meehalkoff✪
02.12.2017
22:30:20

Kirill
02.12.2017
22:31:14
ну я думал в class-based вьюхах через селф)

meehalkoff✪
02.12.2017
22:32:08

Pavel
02.12.2017
23:19:33
в CBV request есть и в параметрах get метода, и в self.request (устанавливается где-то в недрах as_view функции).

Василий
03.12.2017
07:36:02
Можно как то сразу всем объектам модельки поменять значение одного поля, что-бы через for () model.save() не перебирать и много запросов делать, или лучше через транзакцию такое сделать?

Rookie
03.12.2017
07:38:05

Василий
03.12.2017
07:44:54

Google

Artem
03.12.2017
07:45:38
Подскажите пожалуйста, как по нажатию кнопки напротив человека отправлять ему сообщение на эмэйл, при создании человека указывается его эмейл в models.EmailField?

Rookie
03.12.2017
07:46:43

Artem
03.12.2017
08:45:13
ConnectionRefusedError: [WinError 10061] Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение
Кто нибудь сталкивался с такой проблемой, при отправке сообщения на эмейл?

b0g3r
03.12.2017
08:57:51
Смтп сервер неправильно указал?

Artem
03.12.2017
09:00:25
'smtp.gmail.com'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
Привет я windows и я не разрешу тебе отправлять сообщение пока ты не запустишь PyCharm от имени администратора :)

Artem
03.12.2017
09:10:59

Rookie
03.12.2017
09:14:02

Artem
03.12.2017
09:14:22

Rookie
03.12.2017
09:15:57
Сорян) службу:-D
Не, я рили мог отстать. Современные вин поделки не видел, а там и линукс как то встроен, и ещё куча всего. Так что, чего теперь не бывает)

Artem
03.12.2017
09:16:47
Лучше туда даже не соваться;)

Rookie
03.12.2017
09:19:12

Artem
03.12.2017
09:23:39
Я поставил буткамп, а туда: кайф-лайф, altium design, Колин мак ралли 04, и Стим)

Rookie
03.12.2017
09:42:43

Artem
03.12.2017
09:44:17

Rookie
03.12.2017
09:45:45
Ага
Краем уха знакомое название)) Там буткамп есть, и ещё какой то вар, вроде. Хз.

Pavel
03.12.2017
09:50:27

Rookie
03.12.2017
09:52:24

Google

Pavel
03.12.2017
09:53:39
У него необъезженный(
может быть он хотел в пайчарем поднять свой смтп-сервер? Но ведь и линукс не позволит не-руту бинд на порт < 1000.

Rookie
03.12.2017
09:56:03
Ну, я к тому, что это комбайн из гуй обвязки на разные команды.
Хотя. Вот, тот же гит. Я не использую пычармовский терминал (обычная линукс консоль) для гит команд. Там переодически происходят вещи, которые едят мне мозг. Тут же открываю рядом системный, всё работает как должно.

Pavel
03.12.2017
10:05:24

Rookie
03.12.2017
10:05:59

Farrukh
03.12.2017
11:05:39
как можно сериализават content_type в Django Rest Framework?

Pavel
03.12.2017
12:50:03
как можно сериализават content_type в Django Rest Framework?
Далее так:
class TargetObjectRelatedField(serializers.RelatedField):
"""
A custom field to use for the `target_object` generic relationship.
"""
def to_representation(self, value):
"""
Serialize Model1 instances using a Model1 serializer,
and note Model2 using a Model2 serializer.
"""
if isinstance(value, Model1):
serializer = Model1Serializer(value)
elif isinstance(value, Model2):
serializer = Model2Serializer(value)
else:
raise Exception('Unexpected type of target object')
return serializer.data
может я твою задачу не понял, что конкретно требуется


Ahmed
03.12.2017
13:12:13
Ребята, есть проблема с Джангой и мускулом в докере. При запуске двух контейнеров джанги и мускула, джанга не может приконектиться к мускулу. Но если перейти в контейнер в Джанкой выполнить ./manage.py migrate то минрации успешно проходят. В чем может быть проблема? Использую docker-compose

Amirkaaa
03.12.2017
13:17:38
кинь compose
порты ?

Ilya
03.12.2017
13:30:18
Пацаны, глупый вопрос, чем отличается mvc от mvt?

serbernar
03.12.2017
13:31:09

Ilya
03.12.2017
13:31:29
Просто чтобы не быть как все?

serbernar
03.12.2017
13:32:00
О чем ты?
К чему оффтоп?

Google

Rookie
03.12.2017
13:32:14

Ilya
03.12.2017
13:32:38
Просто пытаюсь понять чем view отличается от template

Rookie
03.12.2017
13:33:30

Ilya
03.12.2017
13:33:53
template это разве не шаблон?

serbernar
03.12.2017
13:34:00
Логика работы не изменилась, в любом случае

Alexandr
03.12.2017
13:34:58

Rookie
03.12.2017
13:35:08

Alexandr
03.12.2017
13:35:19

Admin
ERROR: S client not available

Rookie
03.12.2017
13:35:30
вьюха
controller - это view в mvt?

Alexandr
03.12.2017
13:35:59
да

Ilya
03.12.2017
13:36:01
Но тогда почему view это аналог controller?
Как-то не очень логично

Alexandr
03.12.2017
13:36:36
короче модель - модель. контроллер обрабатывает данные и передает во вьюху, которая отрисовывает

Rookie
03.12.2017
13:36:47
Мне по этому и понятнее mvt.

Alexandr
03.12.2017
13:36:52
в джанге вьюха обрабатывает и передает в темплейт
кто с чего начал

serbernar
03.12.2017
13:37:53
те же яйца, только в профиль

Alexandr
03.12.2017
13:38:38
кстати, насколько в джанге часто используется разбиение моделей? например я привык, что каждая модель это отдельный файл. Если я вместо models.py создам папку models, запихну туда файл models.py, куда приинклюдю кучу других файлов с отдельными моделями, то это сильно отходит от джанго вэй?

Google

Ilya
03.12.2017
13:38:47
Погуглил - действительно изобретение джанги

serbernar
03.12.2017
13:39:45

Alexandr
03.12.2017
13:39:56
то есть так можно? отлично
и то же с вьюхами

serbernar
03.12.2017
13:40:07
Только не так
моделс, внутри инит и модели по логике

Alexandr
03.12.2017
13:40:37
превратим джангу в yii)

Rookie
03.12.2017
13:40:51

Alexandr
03.12.2017
13:40:51
инит це что?

serbernar
03.12.2017
13:41:11
Ты просто большие проекты не видел

Rookie
03.12.2017
13:41:47

serbernar
03.12.2017
13:42:05

Rookie
03.12.2017
13:42:21

Alexandr
03.12.2017
13:42:23
в пыхе 300 мб это тока папка вендоров)

Rookie
03.12.2017
13:43:14

serbernar
03.12.2017
13:43:33
Хотя, думаю большой, да

Alexandr
03.12.2017
13:43:37
да много это)
я понял о чем ты

Valentin
03.12.2017
13:44:21

Alexandr
03.12.2017
13:44:29
это понятно

Rookie
03.12.2017
13:44:32
Хотя. Я думаю, что структура - это просто важно для навигации потом при поддержке.