티스토리 뷰
이번글에서는 도커를 활용하여 웹서비스를 배포하겠습니다.
PostgreSQL이 가동 중인지 확인합니다.
user@myserver01:~$ systemctl status postgresql
Unit postgresql.service could not be found.
만약에 존재하지 않는다면 설치합니다.
https://www.postgresql.org/download/linux/ubuntu/
sudo apt install curl ca-certificates
sudo install -d /usr/share/postgresql-common/pgdg
sudo curl -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc --fail https://www.postgresql.org/media/keys/ACCC4CF8.asc
sudo sh -c 'echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
sudo apt update
sudo apt -y install postgresql
설치 후 확인
user@myserver01:~$ systemctl status postgresql ● postgresql.service - PostgreSQL RDBMS
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; preset: enabled)
Active: active (exited) since Thu 2025-01-16 00:07:23 UTC; 43s ago
Main PID: 7190 (code=exited, status=0/SUCCESS)
CPU: 5ms
Jan 16 00:07:23 myserver01 systemd[1]: Starting postgresql.service - PostgreSQL RDBMS...
Jan 16 00:07:23 myserver01 systemd[1]: Finished postgresql.service - PostgreSQL RDBMS.
user@myserver01:~$ ^C
user@myserver01:~$ systemctl status postgresql
● postgresql.service - PostgreSQL RDBMS
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; preset: enabled)
Active: active (exited) since Thu 2025-01-16 00:07:23 UTC; 2min 1s ago
Main PID: 7190 (code=exited, status=0/SUCCESS)
CPU: 5ms
Jan 16 00:07:23 myserver01 systemd[1]: Starting postgresql.service - PostgreSQL RDBMS...
Jan 16 00:07:23 myserver01 systemd[1]: Finished postgresql.service - PostgreSQL RDBMS.
1. pyenv 설치
django 라이브러리를 활용할 예정이므로 pyenv를 설치합니다. pyenv는 파이썬 가상환경을 관리할 수 있게 해주는 소프트웨어입니다.
https://github.com/pyenv/pyenv?tab=readme-ov-file#linuxunix
curl -fsSL https://pyenv.run | bash
세부 설정
root@myserver01:~# echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
root@myserver01:~# echo '[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
root@myserver01:~# echo 'eval "$(pyenv init - bash)"' >> ~/.bashrc
root@myserver01:~# echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bashrc
환경설정 적용 후 설치 확인
root@myserver01:~# exec $SHELL
root@myserver01:~# pyenv
pyenv 2.5.0
Usage: pyenv <command> [<args>]
..생략..
pyenv를 활용해 파이썬 가상환경을 구축합니다.
설치 가능한 파이썬 버전을 확인합니다.
root@myserver01:~# pyenv install --list
...생략
3.13.1
..
2. django, nginx, postgresl 연동
파이썬 필수 라이브러리 설치
sudo apt update
sudo apt install -y \
build-essential \
libssl-dev \
zlib1g-dev \
libbz2-dev \
libreadline-dev \
libsqlite3-dev \
wget \
curl \
llvm \
libncurses5-dev \
libncursesw5-dev \
xz-utils \
tk-dev \
libffi-dev \
liblzma-dev \
python3-openssl \
git
파이썬 설치
root@myserver01:~# pyenv install 3.13.1
Downloading Python-3.13.1.tar.xz...
-> https://www.python.org/ftp/python/3.13.1/Python-3.13.1.tar.xz
Installing Python-3.13.1...
Installed Python-3.13.1 to /root/.pyenv/versions/3.13.1
설치 중 멈춘것 같아도 정상 다운로드 중이니 차분히 기다리십시오
설치 확인
root@myserver01:~# pyenv versions
* system (set by /root/.pyenv/version)
3.13.1
pyenv virtualenv 명령어로 py3_13_1 이라는 가상환경을 만듭니다.
root@myserver01:~# pyenv virtualenv 3.13.1 py3_13_1
설치 확인
root@myserver01:~# pyenv versions
* system (set by /root/.pyenv/version)
3.13.1
3.13.1/envs/py3_13_1
py3_13_1 --> /root/.pyenv/versions/3.13.1/envs/py3_13_1
생성한 가상환경을 실행합니다.
root@myserver01:~# pyenv activate py3_13_1
(py3_13_1) root@myserver01:~# pip install django
(py3_13_1) root@myserver01:~# pip install gunicorn
(py3_13_1) root@myserver01:~# pip install psycopg2-binary
(py3_13_1) root@myserver01:~# pip install pyyaml
필요한 파이썬 라이브러리를 설치합니다 웹 프레임워크인 django를 설치합니다.
웹서버와 통신하기 위한 라이브러리인 gunicorn을 설치합니다.
파이썬에서 PostgreSQL을 활용하기 위해 사용하는 psycopg2-binary를 설치합니다.
파이썬에서 yaml파일을 다룰 수 있게 도와주는 pyyaml을 설치합니다.
정상설치 확인 후 파이썬과 가상환경 종료
(py3_13_1) root@myserver01:~# python
Python 3.13.1 (main, Jan 16 2025, 01:03:27) [GCC 13.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> import gunicorn
>>> import psycopg2
>>> import yaml
>>> django.__version__
'5.1.5'
>>> gunicorn.__version__
'23.0.0'
>>> psycopg2.__version__
'2.9.10 (dt dec pq3 ext lo64)'
>>> yaml.__version__
'6.0.2'
>>> quit()
(py3_13_1) root@myserver01:~# pyenv deactivate
포드포워딩 설정
8000 TCP와 80 TCP 추가
django-admin 명령어로 myapp이라는 프로젝트를 만듭니다.
root@myserver01:/home/work# mkdir ch17
root@myserver01:/home/work# cd ch17
root@myserver01:/home/work/ch17# pyenv activate py3_13_1
(py3_13_1) root@myserver01:/home/work/ch17# django-admin startproject myapp
외부에서 접근가능하도록 ALLOWED_HOSTS = [] 을 작은 따옴표 '*' 을 추가하여 ALLOWED_HOSTS = ['*'] 로 변경합니다.
(py3_13_1) root@myserver01:/home/work/ch17# ls
myapp
(py3_13_1) root@myserver01:/home/work/ch17# cd myapp/myapp/
(py3_13_1) root@myserver01:/home/work/ch17/myapp/myapp# vi settings.py
...생략
ALLOWED_HOSTS = ['*']
migrate 로 실제 데이터베이스에 변경사항을 저장합니다.
(py3_13_1) root@myserver01:/home/work/ch17/myapp/myapp# cd ..
(py3_13_1) root@myserver01:/home/work/ch17/myapp# ls
manage.py myapp
(py3_13_1) root@myserver01:/home/work/ch17/myapp# python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
....생략
(py3_13_1) root@myserver01:/home/work/ch17/myapp# python manage.py runserver
Watching for file changes with StatReloader
....생략
http://127.0.0.1:8000/ 로 접속하여 확인
도커 이미지를 생성하기 위해 필요한 설치 파일 목록인 requirements.txt파일을 생성합니다.
(py3_13_1) root@myserver01:/home/work/ch17/myapp# pyenv deactivate
root@myserver01:/home/work/ch17# vi requirements.txt
django==5.1.5
도커 이미지 파일을 생성하기 위해 필요한 명령어를 모아놓은 파일을 Dockerfile이라고 합니다. 다음은 Dockerfile을 생성합니다.
root@myserver01:/home/work/ch17# vi Dockerfile
FROM python:3.13.1
WORKDIR /usr/src/app
COPY . .
RUN python -m pip install --upgrade pip
RUN pip install -r requirements.txt
WORKDIR ./myapp
CMD python manage.py runserver 0.0.0.0:8000
EXPOSE 8000
FROM을 사용하여 베이스 이미지를 작성합니다.
WORKDIR 명령어는 cd 명령어와 비슷한 명령어로 , 디렉터리를 전환할때 사용합니다.
COPY 명령어는 호스트에 존재하는 파일을 도커 이미지의 파일 시스템 경로로 복사하는 명령어입니다.
COPY <호스트파일경로> : <이미지파일 경로> COPY . . 명령어는 현재 경로에 존재하는 내부 파일을 이미지 파일 경로의 현재 경로 /usr/src/app으로 복사한다는 의미입니다.
RUN 명령어는 실행하고 싶은 명령어가 있을때에 사용합니다.
requirements.txt파일 내부에 존재하는 파일을 설치합니다.
EXPOSE 명령어를 통해 8000포트를 엽니다.
도커 이미지 빌드하기
root@myserver01:/home/work/ch17# docker image build . -t myweb01
[+] Building 88.1s (11/11) FINISHED docker:default
=> [internal] load build definition from Dockerfile 0.1s
=> => transferring dockerfile: 243B
...생략............
build 명령어를 사용하여 도커 이미지를 생성합니다. build에서 . 은 현재 디렉터리를 이미지로 빌드하겠다는 뜻입니다. 그리고 -t 옵션은 이미지 태그를 정할때 사용합니다.
설치 확인
root@myserver01:/home/work/ch17# docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
myweb01 latest 78496462f0e9 49 seconds ago 1.07GB
도커 이미지를 컨테이너 형태로 배포합니다.
root@myserver01:/home/work/ch17# docker container run -d -p 8000:8000 myweb01
9e598cb3df948a0d7da1ed649e052776649592248fb0b52287a335e0a770a968
root@myserver01:/home/work/ch17# docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9e598cb3df94 myweb01 "/bin/sh -c 'python …" 9 seconds ago Up 8 seconds 0.0.0.0:8000->8000/tcp, :::8000->8000/tcp quizzical_mcnulty
-d 옵션은 백그라운드에서 실행하는 것을 의미하고, -p옵션은 포트포워딩 옵션입니다.
-p <도커 호스트 포트 > : <컨테이너 포트>
inspect 명령어로 실행중인 컨테이너 IP 주소를 확인합니다.
root@myserver01:/home/work/ch17# docker network inspect bridge | grep IPv4Address
"IPv4Address": "172.17.0.2/16",
nginx컨테이너를 실행하고 gunicorn을 통해 nginx와 django를 연동하겠습니다.
root@myserver01:/home/work# mkdir ch18
root@myserver01:/home/work# cd ch18/
root@myserver01:/home/work/ch18# vi Dockerfile
FROM nginx:1.25.3
CMD ["nginx", "-g","daemon off;"]
CMD 명령어를 사용할때는 대괄호를 사용하는 방법과 사용하지 않는 방법이 있습니다.
대괄호를 사용하지 않으면 명령어 전체가 문자열로 인식합니다.
만약 대괄호를 사용한다면, json형태로 전달되어 '-' 와 같은 특수문자를 활용할때 정확성이 향상됩니다.
컨테이너를 활용해 Nginx를 실행할때는 daemon off 옵션을 활용해 포그라운드 foreground로 실행해주어야 합니다.
docker image build 명령어로 이미지를 빌드합니다.
root@myserver01:/home/work/ch18# docker image build . -t mynginx01
[+] Building 18.0s (5/5) FINISHED docker:default
=> [internal] load build definition from Dockerfile 0.1s
..생략...
=> => naming to docker.io/library/mynginx01 0.0s
root@myserver01:/home/work/ch18# docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
myweb01 latest 78496462f0e9 18 minutes ago 1.07GB
mynginx01 latest 119ab5182382 14 months ago 187MB
빌드한 이미지를 활용해 컨테이너를 실행합니다.
root@myserver01:/home/work/ch18# docker container run -p 80:80 -d mynginx01
76db3e8d2bda57286981a02e2d2dfd60c3a700082fc8e50d3ae0297be5220cf6
nginx 내부 설정 파일 확인
root@myserver01:/home/work/ch18# docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
76db3e8d2bda mynginx01 "/docker-entrypoint.…" About a minute ago Up About a minute 0.0.0.0:80->80/tcp, :::80->80/tcp optimistic_carson
9e598cb3df94 myweb01 "/bin/sh -c 'python …" 19 minutes ago Up 19 minutes 0.0.0.0:8000->8000/tcp, :::8000->8000/tcp quizzical_mcnulty
root@myserver01:/home/work/ch18# docker container exec -it 76db3e8d2bda /bin/bash
root@76db3e8d2bda:/# cd /etc/nginx/conf.d/
root@76db3e8d2bda:/etc/nginx/conf.d# ls
default.conf
root@76db3e8d2bda:/etc/nginx/conf.d# cat default.conf
server {
listen 80;
listen [::]:80;
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
...생략
root@76db3e8d2bda:/etc/nginx/conf.d# exit
exit
모두 종료
root@myserver01:/home/work/ch18# docker container stop 76db3e8d2bda 9e598cb3df94
76db3e8d2bda
9e598cb3df94
소스 수정
root@myserver01:/home/work# mkdir ch19
root@myserver01:/home/work# cp -r ch17 ch18 ch19
root@myserver01:/home/work# cd ch19
root@myserver01:/home/work/ch19# ls -al
total 16
drwxr-xr-x 4 root root 4096 Jan 16 02:25 .
drwxr-xr-x 24 root root 4096 Jan 16 02:23 ..
drwxr-xr-x 3 root root 4096 Jan 16 02:25 ch17
drwxr-xr-x 2 root root 4096 Jan 16 02:25 ch18
root@myserver01:/home/work/ch19# mv ch17 myDjango02
root@myserver01:/home/work/ch19# mv ch18 myNginx02
설치 파일 수정
root@myserver01:/home/work/ch19# cd myDjango02
root@myserver01:/home/work/ch19/myDjango02# ls -al
total 20
drwxr-xr-x 3 root root 4096 Jan 16 02:25 .
drwxr-xr-x 4 root root 4096 Jan 16 02:26 ..
-rw-r--r-- 1 root root 204 Jan 16 02:25 Dockerfile
drwxr-xr-x 3 root root 4096 Jan 16 02:25 myapp
-rw-r--r-- 1 root root 14 Jan 16 02:25 requirements.txt
root@myserver01:/home/work/ch19/myDjango02# vi requirements.txt
django==5.1.5
gunicorn==23.0.0
Dockerfile을 수정합니다.
root@myserver01:/home/work/ch19/myDjango02# vi Dockerfile
FROM python:3.13.1
WORKDIR /usr/src/app
COPY . .
RUN python -m pip install --upgrade pip
RUN pip install -r requirements.txt
WORKDIR ./myapp
CMD gunicorn --bind 0.0.0.0:8000 myapp.wsgi:application
EXPOSE 8000
이미지를 빌드합니다.
root@myserver01:/home/work/ch19/myDjango02# docker image build . -t myweb02
[+] Building 12.1s (11/11) FINISHED docker:default
=> [internal] load build definition from Dockerfile
..생략....
root@myserver01:/home/work/ch19/myDjango02# docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
myweb02 latest ccfb326fc3a2 31 seconds ago 1.07GB
nginx 이미지 수정
root@myserver01:/home/work/ch19/myDjango02# cd ../myNginx02/
root@myserver01:/home/work/ch19/myNginx02# vi default.conf
upstream myweb {
server djangotest:8000;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://myweb;
}
}
djangotest는 django를 이용해 생성하게 될 컨테이너 이름입니다. 즉 Nginx는 80포트로 받은 요청을 djangotest 컨테이너의 8000포트로 전송하겠다는 뜻입니다.
Dockerfile 수정
root@myserver01:/home/work/ch19/myNginx02# ls -al
total 16
drwxr-xr-x 2 root root 4096 Jan 16 02:39 .
drwxr-xr-x 4 root root 4096 Jan 16 02:26 ..
-rw-r--r-- 1 root root 159 Jan 16 02:39 default.conf
-rw-r--r-- 1 root root 52 Jan 16 02:25 Dockerfile
root@myserver01:/home/work/ch19/myNginx02# vi Dockerfile
FROM nginx:1.25.3
RUN rm /etc/nginx/conf.d/default.conf
COPY default.conf /etc/nginx/conf.d/
CMD ["nginx", "-g","daemon off;"]
nginx에서 사용하는 설정파일을 삭제하고 생성한 default.conf파일을 사용한다는 뜻입니다.
이미지를 빌드합니다.
root@myserver01:/home/work/ch19/myNginx02# docker image build . -t mynginx02
[+] Building 2.7s (8/8) FINISHED docker:default
=> [internal] load build definition from Dockerfile
..생략...
root@myserver01:/home/work/ch19/myNginx02# docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
mynginx02 latest 89b7f80401b7 16 seconds ago 187MB
django와 nginx 이미지를 모두 빌드하였습니다. 이제 django와 nginx를 연동해서 컨테이너를 실행하겠습니다.
현재 네트워크 목록을 조회합니다.
root@myserver01:/home/work/ch19/myNginx02# docker network ls
NETWORK ID NAME DRIVER SCOPE
57e56a840ee9 bridge bridge local
e25e86151666 host host local
13b774376851 none null local
새로운 네트워크를 생성합니다.
root@myserver01:/home/work/ch19/myNginx02# docker network create mynetwork02
c307c7942fa11ae42154bc4219289a8653f9307387c29047983c82b5a401ebd8
django 컨테이너를 실행합니다.
root@myserver01:/home/work/ch19/myNginx02# docker container run -d --name djangotest --network mynetwork02 myweb02
a45fd52020ccbcb87540346a38567871516e8060db0292ba836dc7c37335351f
컨테이너 이름은 djangotest이고 네트워크는 mynetwork02를 사용합니다.
nginx 컨테이너를 실행합니다.
root@myserver01:/home/work/ch19/myNginx02# docker container run -d --name nginxtest --network mynetwork02 -p 80:80 mynginx02
7bd1c519d177ac355680c73638adce7a90e977a5c9a526232de87796bdf03398
연동 확인 후 컨테이너를 정지합니다.
root@myserver01:/home/work/ch19/myNginx02# docker container stop 7bd1c519d177 a45fd52020cc
7bd1c519d177
a45fd52020cc
도커를 활용해 PostgreSQL를 배포하겠습니다.
root@myserver01:/home/work# mkdir ch20
root@myserver01:/home/work# cd ch20
root@myserver01:/home/work/ch20# psql --version
psql (PostgreSQL) 17.2 (Ubuntu 17.2-1.pgdg24.04+1)
root@myserver01:/home/work/ch20# vi Dockerfile
FROM postgres:17.2
이미지를 생성합니다.
root@myserver01:/home/work/ch20# docker image build . -t mypostgres03
[+] Building 29.6s (5/5) FINISHED docker:default
=> [internal] load build definition from Dockerfile 0.1s
=> => transferring dockerfile: 56B
..생략..
root@myserver01:/home/work/ch20# docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
mypostgres03 latest 9a0ce6be5dd4 7 weeks ago 435MB
빌드한 이미지를 활용해 컨테이너를 실행합니다.
root@myserver01:/home/work/ch20# docker container run -e POSTGRES_PASSWORD=mysecretpassword \
--mount type=volume,source=myvolume03,target=/var/lib/postgresql/data \
-d mypostgres03
115b741217c1c2ff2289eab91566df14bfe0c57e4d48210cf8b6bbd2b59a85e0
-e 변수로 환경변수를 설정합니다.
--mount 옵션을 활용해 도커 볼륨과 볼륨에 대한 내용을 설정합니다.
컨테이너 목록 확인 후 컨테이너 정지
root@myserver01:/home/work/ch20# docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
115b741217c1 mypostgres03 "docker-entrypoint.s…" 3 minutes ago Up 3 minutes 5432/tcp blissful_wright
root@myserver01:/home/work/ch20# docker container stop 115b741217c1
115b741217c1
django, nginx, postgresql 연동을 합니다.
root@myserver01:/home/work# cp -r ch19 ch21
root@myserver01:/home/work# cp -r ch20 ch21
root@myserver01:/home/work# cd ch21
root@myserver01:/home/work/ch21# ls -al
total 20
drwxr-xr-x 5 root root 4096 Jan 16 04:26 .
drwxr-xr-x 26 root root 4096 Jan 16 04:26 ..
drwxr-xr-x 2 root root 4096 Jan 16 04:26 ch20
drwxr-xr-x 3 root root 4096 Jan 16 04:26 myDjango02
drwxr-xr-x 2 root root 4096 Jan 16 04:26 myNginx02
root@myserver01:/home/work/ch21# mv ch20 myPostgres03
root@myserver01:/home/work/ch21# mv myDjango02 myDjango03
root@myserver01:/home/work/ch21# mv myNginx02 myNginx03
root@myserver01:/home/work/ch21# ls
myDjango03 myNginx03 myPostgres03
django 내부의 settings.py 파일부터 수정합니다.
root@myserver01:/home/work/ch21# cd myDjango03
root@myserver01:/home/work/ch21/myDjango03# ls
Dockerfile myapp requirements.txt
root@myserver01:/home/work/ch21/myDjango03# cd myapp/myapp/
root@myserver01:/home/work/ch21/myDjango03/myapp/myapp# vi settings.py
..생략..
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'mysecretpassword',
'HOST':'postgrestest',
'PORT': 5432
}
}
postgresql 설정 정보를 작성합니다 이때 HOST 항목에는 postgreSQL 컨테이너 이름으로 작성합니다.
requirements.txt 를 수정합니다.
root@myserver01:/home/work/ch21/myDjango03# ls
Dockerfile myapp requirements.txt
root@myserver01:/home/work/ch21/myDjango03# vi requirements.txt
django==5.1.5
gunicorn==23.0.0
psycopg2==2.9.10
도커 이미지를 빌드합니다.
root@myserver01:/home/work/ch21/myDjango03# docker image build . -t myweb03
[+] Building 27.2s (11/11) FINISHED docker:default
=> [internal] load build definition from Dockerfile 0.1s
=> => transferring dockerfile: 256B
..생략
root@myserver01:/home/work/ch21/myDjango03# docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
myweb03 latest b49090f265c9 5 seconds ago 1.07GB
nginx 이미지 빌드
root@myserver01:/home/work/ch21/myNginx03# docker image build . -t mynginx03
[+] Building 1.9s (8/8) FINISHED docker:default
=> [internal] load build definition from Dockerfile 0.1s
..생략... 0.0s
root@myserver01:/home/work/ch21/myNginx03# docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
myweb03 latest b49090f265c9 About a minute ago 1.07GB
호스트에서 웹 브라우저를 실행한 후 127.0.0.1:80 에 접속하면 포트포워딩을 통해 10.0.2.4:80으로 트래픽이 전달됩니다.
이후 nginxtest컨테이너를 거쳐, djangotest 컨테이너에 접속할 수 있으며, djangotest 컨테이너는 postgretest 컨테이너를 통해 데이터베이스를 활용할 수 있습니다.
새 네트워크를 생성합니다.
root@myserver01:/home/work/ch21/myNginx03# docker network create mynetwork03
1c589f715f0f0817ab00070834c0595442308ad7cbbb37577bcfd3d9bb984e75
root@myserver01:/home/work/ch21/myNginx03# docker network ls
NETWORK ID NAME DRIVER SCOPE
57e56a840ee9 bridge bridge local
e25e86151666 host host local
c307c7942fa1 mynetwork02 bridge local
1c589f715f0f mynetwork03 bridge local
13b774376851 none null local
PostgreSQL컨테이너를 실행합니다.
root@myserver01:/home/work/ch21/myNginx03# docker container run --name postgrestest --network mynetwork03 \
-e POSTGRES_PASSWORD=mysecretpassword \
--mount type=volume,source=myvolume03,target=/var/lib/postgresql/data \
-d mypostgres03
6e4852d6653db73dd11c3047792c771ea60c5c708d3f87d4d177afb2bce72aa4
컨테이너명은 postgrestest이며 네트워크는 mynetwork03을 사용합니다.
-e 옵션으로 PostgreSQL 컨테이너의 환경 변수를 설정합니다.
--mount 옵션으로 도커볼륨을 설정합니다.
-d 옵션으로 백그라운드로 mypostgres03 이미지를 활용해 컨테이너를 실행합니다.
기존 사용하던 컨테이너 삭제 후 django 컨테이너를 실행합니다.
root@myserver01:/home/work/ch21/myNginx03# docker rm -f djangotest
root@myserver01:/home/work/ch21/myNginx03# docker container run -d --name djangotest --network mynetwork03 myweb03
2fd13ee1068874bcde3dc2c39ad4d01d0916a9afcb57b12c4dc4406a18ffe696
root@myserver01:/home/work/ch21/myNginx03# docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2fd13ee10688 myweb03 "/bin/sh -c 'gunicor…" 28 seconds ago Up 28 seconds 8000/tcp djangotest
6e4852d6653d mypostgres03 "docker-entrypoint.s…" 8 minutes ago Up 8 minutes 5432/tcp postgrestest
nginx 컨테이너를 실행합니다.
root@myserver01:/home/work/ch21/myNginx03# docker rm -f nginxtest
nginxtest
root@myserver01:/home/work/ch21/myNginx03# docker container run -d --name nginxtest --network mynetwork03 -p 80:80 mynginx03
ca1a3b67c9b93fd398eb7f23b6348c7af2c95d1f7668ac47062a5cc845754cbb
django와 postgreSQL이 연결되어있는지 확인합니다.
root@myserver01:/home/work/ch21/myNginx03# docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ca1a3b67c9b9 mynginx03 "/docker-entrypoint.…" About a minute ago Up About a minute 0.0.0.0:80->80/tcp, :::80->80/tcp nginxtest
2fd13ee10688 myweb03 "/bin/sh -c 'gunicor…" 7 minutes ago Up 7 minutes 8000/tcp djangotest
6e4852d6653d mypostgres03 "docker-entrypoint.s…" 15 minutes ago Up 15 minutes 5432/tcp postgrestest
root@myserver01:/home/work/ch21/myNginx03# docker container exec -it 2fd13ee10688 /bin/bash
root@2fd13ee10688:/usr/src/app/myapp# python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
root@2fd13ee10688:/usr/src/app/myapp# exit
exit
모든 컨테이너를 중지합니다.
root@myserver01:/home/work/ch21/myNginx03# docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ca1a3b67c9b9 mynginx03 "/docker-entrypoint.…" 6 minutes ago Up 6 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp nginxtest
2fd13ee10688 myweb03 "/bin/sh -c 'gunicor…" 13 minutes ago Up 13 minutes 8000/tcp djangotest
6e4852d6653d mypostgres03 "docker-entrypoint.s…" 21 minutes ago Up 21 minutes 5432/tcp postgrestest
root@myserver01:/home/work/ch21/myNginx03# docker container stop ca1a3b67c9b9 2fd13ee10688 6e4852d6653d
ca1a3b67c9b9
2fd13ee10688
6e4852d6653d
3. 도커 컴포즈로 실행하기
user@myserver01:/home/work/ch21$ sudo vi docker-compose.yml
services:
djangotest:
build: ./myDjango03
networks:
- composenet01
depends_on:
- postgrestest
restart: always
nginxtest:
build: ./myNginx03
networks:
- composenet01
ports:
- "80:80"
depends_on:
- djangotest
restart: always
postgrestest:
build: ./myPostgres03
networks:
- composenet01
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: mysecretpassword
POSTGRES_DB: postgres
volumes:
- composenet01:/var/lib/postgresql/data
restart: always
networks:
composenet01:
volumes:
composenet01:
django를 활용한 서비스명을 djangotest로 지었습니다. 이미지를 빌드할 경로는 ./myDjango03입니다.
해당 서비스를 사용할 네트워크 명은 composenet01입니다.
depends_on은 컨테이너 실행 순서를 정할때 사용합니다.postgrestest가 입력되었다면 postgrestest 먼저 실행후 djangotest를 나중에 실행합니다.
restart: always 는 컨테이너가 종료되면 재실행하라는 명령어 입니다.
composenet01:/var/lib/postgresql/data는 composenet01이라는 볼륨을 PostgreSQL 컨테이너 내부의 /var/lib/postgresql/data 경로에 마운트하겠다는 뜻입니다.
user@myserver01:/home/work/ch21$ sudo docker compose up -d --build
[+] Building 5.5s (30/30) FINISHED docker:default
=> [postgrestest internal] load build definition from Dockerfile 0.1s
=> => transferring dockerfile: 56B
..생략
✔ djangotest Built 0.0s
✔ nginxtest Built 0.0s
✔ postgrestest Built 0.0s
✔ Network ch24_composenet01 Created 0.3s
✔ Volume "ch24_composenet01" Created 0.0s
✔ Container ch24-postgrestest-1 Started 2.1s
✔ Container ch24-djangotest-1 Started 2.9s
✔ Container ch24-nginxtest-1 Started
모두 종료
user@myserver01:/home/work/ch21$ sudo docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
46f069537d0e ch24-nginxtest "/docker-entrypoint.…" About a minute ago Up About a minute 0.0.0.0:80->80/tcp, :::80->80/tcp ch24-nginxtest-1
edc6a05eabf5 ch24-djangotest "/bin/sh -c 'gunicor…" About a minute ago Up About a minute 8000/tcp ch24-djangotest-1
260bb7dee4ea ch24-postgrestest "docker-entrypoint.s…" About a minute ago Up About a minute 5432/tcp ch24-postgrestest-1
user@myserver01:/home/work/ch24$ sudo -i
root@myserver01:~# docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
46f069537d0e ch24-nginxtest "/docker-entrypoint.…" 2 minutes ago Up 2 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp ch24-nginxtest-1
edc6a05eabf5 ch24-djangotest "/bin/sh -c 'gunicor…" 2 minutes ago Up 2 minutes 8000/tcp ch24-djangotest-1
260bb7dee4ea ch24-postgrestest "docker-entrypoint.s…" 2 minutes ago Up 2 minutes 5432/tcp ch24-postgrestest-1
user@myserver01:/home/work/ch21$ sudo docker compose down
[+] Running 4/4
✔ Container ch24-nginxtest-1 Removed 0.4s
✔ Container ch24-djangotest-1 Removed 10.4s
✔ Container ch24-postgrestest-1 Removed 0.5s
✔ Network ch24_composenet01 Removed
postgreSQL에 접속하며 원하는 비밀번호로 변경합니다.
root@myserver01:/home/work/ch21/myNginx03# sudo -i -u postgres
postgres@myserver01:~$ psql
psql (17.2 (Ubuntu 17.2-1.pgdg24.04+1))
Type "help" for help.
postgres=# \list
List of databases
Name | Owner | Encoding | Locale Provider | Collate | Ctype | Locale | ICU Rules | Access privileges
-----------+----------+----------+-----------------+-------------+-------------+--------+-----------+-----------------------
postgres | postgres | UTF8 | libc | en_US.UTF-8 | en_US.UTF-8 | | |
template0 | postgres | UTF8 | libc | en_US.UTF-8 | en_US.UTF-8 | | | =c/postgres +
| | | | | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | libc | en_US.UTF-8 | en_US.UTF-8 | | | =c/postgres +
| | | | | | | | postgres=CTc/postgres
(3 rows)
postgres=# \password
Enter new password for user "postgres":
Enter it again:
postgres=# \q
postgres@myserver01:~$ exit
logout
외부에서도 PostgreSQL에 접속할 수 있도록 설정합니다.
root@myserver01:/home/work/ch21/myNginx03# cd /etc/postgresql/17/main
root@myserver01:/etc/postgresql/17/main# ls
conf.d environment pg_ctl.conf pg_hba.conf pg_ident.conf postgresql.conf start.conf
root@myserver01:/etc/postgresql/17/main# vi pg_hba.conf
local all postgres peer
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all peer
# IPv4 local connections:
host all all 127.0.0.1/32 scram-sha-256
host all all 0.0.0.0/0 scram-sha-256
# IPv6 local connections:
host all all ::1/128 scram-sha-256
# Allow replication connections from localhost, by a user with the
# replication privilege.
local replication all peer
host replication all 127.0.0.1/32 scram-sha-256
host replication all ::1/128 scram-sha-256
host all all 0.0.0.0/0 scram-sha-256 을 추가하였습니다.
PostgreSQL 서버가 어떤 클라이언트의 요청을 수락할 것인지 설정합니다.
root@myserver01:/etc/postgresql/17/main# vi postgresql.conf
listen_addresses = '*' # what IP address(es) to listen on;
...생략..
설정 후 postgreSQL 서비스 재시작
root@myserver01:/etc/postgresql/17/main# systemctl restart postgresql
root@myserver01:/etc/postgresql/17/main# systemctl status postgresql.service
● postgresql.service - PostgreSQL RDBMS
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; preset: enabled)
Active: active (exited) since Thu 2025-01-16 05:32:13 UTC; 12s ago
Process: 41527 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
Main PID: 41527 (code=exited, status=0/SUCCESS)
CPU: 4ms
Jan 16 05:32:13 myserver01 systemd[1]: Finished postgresql.service - PostgreSQL RDBMS.
django이미지를 빌드합니다.
root@myserver01:/home/work# cp -r ch21 ch22
root@myserver01:/home/work# cd ch22
root@myserver01:/home/work/ch22# ls
myDjango03 myNginx03 myPostgres03
root@myserver01:/home/work/ch22# rm -r myPostgres03
root@myserver01:/home/work/ch22# mv myDjango03 myDjango04
root@myserver01:/home/work/ch22# mv myNginx03 myNginx04
root@myserver01:/home/work/ch22# ls
myDjango04 myNginx04
docker0의 IP 주소를 확인합니다.
root@myserver01:/home/work/ch22# ifconfig
..생략
docker0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
inet 172.17.0.1 netmask 255.255.0.0 broadcast 172.17.255.255
inet6 fe80::42:b7ff:fe88:1bee prefixlen 64 scopeid 0x20<link>
ether 02:42:b7:88:1b:ee txqueuelen 0 (Ethernet)
RX packets 3283 bytes 187333 (187.3 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 6096 bytes 28265653 (28.2 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
django에 DB정보 변경
root@myserver01:/home/work/ch22# cd myDjango04/
root@myserver01:/home/work/ch22/myDjango04# cd myapp/myapp/
root@myserver01:/home/work/ch22/myDjango04/myapp/myapp# vi settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': '설정한DB비밀번호',
'HOST':'172.17.0.1',
'PORT': 5432
}
}
설정한 django 이미지를 빌드합니다.
root@myserver01:/home/work/ch22/myDjango04/myapp/myapp# cd ../..
root@myserver01:/home/work/ch22/myDjango04# docker image build . -t myweb04
nginx 이미지를 빌드합니다.
root@myserver01:/home/work/ch22/myDjango04# cd ../myDjango04/
root@myserver01:/home/work/ch22/myNginx04# docker image build . -t mynginx04
[+] Building 2.0s (8/8) FINISHED
도커 네트워크를 생성합니다.
root@myserver01:/home/work/ch22/myNginx04# docker network create mynetwork04
befde4ca04ede6882d99999cc395264429c2c34ded81e30c3ee71b31ecd120be
root@myserver01:/home/work/ch22/myNginx04# docker network ls
NETWORK ID NAME DRIVER SCOPE
befde4ca04ed mynetwork04 bridge local
django 컨테이너를 실행합니다.
root@myserver01:/home/work/ch22/myNginx04# docker rm -f djangotest
djangotest
root@myserver01:/home/work/ch22/myNginx04# docker container run -d --name djangotest --network mynetwork04 myweb04
5ae69c7d35a8bee9363fe4dbec759c9690a342aa4c99dedd5c5311b147ca5860
nginx 컨테이너를 실행합니다.
root@myserver01:/home/work/ch22/myNginx04# docker rm -f nginxtest
nginxtest
root@myserver01:/home/work/ch22/myNginx04# docker container run -d --name nginxtest --network mynetwork04 -p 80:80 mynginx04
c2bc32485a3770750e7df5121821eea54a5dc2ff735f001bfe320f02da806662
실행 중인 컨테이너를 확인합니다.
root@myserver01:/home/work/ch22/myNginx04# docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c2bc32485a37 mynginx04 "/docker-entrypoint.…" 24 seconds ago Up 23 seconds 0.0.0.0:80->80/tcp, :::80->80/tcp nginxtest
5ae69c7d35a8 myweb04 "/bin/sh -c 'gunicor…" 2 minutes ago Up 2 minutes 8000/tcp djangotest
django와 postgresql이 연결되었는지 확인합니다.
root@myserver01:/home/work/ch22/myNginx04# docker container exec -it 5ae69c7d35a8 /bin/bash
root@5ae69c7d35a8:/usr/src/app/myapp# ls
db.sqlite3 manage.py myapp
root@5ae69c7d35a8:/usr/src/app/myapp# python manage.py inspectdb
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models
root@5ae69c7d35a8:/usr/src/app/myapp# exit
exit
내부 접속 후 manage.py 파일이 존재하는 것을 확인합니다.
컨테이너를 모두 중지합니다.
root@myserver01:/home/work/ch22/myNginx04# docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c2bc32485a37 mynginx04 "/docker-entrypoint.…" 4 minutes ago Up 4 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp nginxtest
5ae69c7d35a8 myweb04 "/bin/sh -c 'gunicor…" 6 minutes ago Up 6 minutes 8000/tcp djangotest
root@myserver01:/home/work/ch22/myNginx04# docker container stop c2bc32485a37 5ae69c7d35a8
c2bc32485a37
5ae69c7d35a8
도커 컴포즈를 활용하여 컨테이너를 실행합니다.
user@myserver01:/home/work/ch22$ sudo vi docker-compose.yml
services:
djangotest:
build: ./myDjango04
networks:
- composenet01
restart: always
nginxtest:
build: ./myNginx04
networks:
- composenet01
ports:
- "80:80"
depends_on:
- djangotest
restart: always
networks:
composenet01:
user@myserver01:/home/work/ch22$ sudo docker compose up -d --build
[+] Building 3.4s (23/23) FINISHED docker:default
=> [djangotest internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 256B
..생략...
[+] Running 5/5
✔ djangotest Built 0.0s
✔ nginxtest Built 0.0s
✔ Network ch22_composenet01 Created 0.2s
✔ Container ch22-djangotest-1 Started 1.0s
✔ Container ch22-nginxtest-1 Started
실행 중인 django 내부에 접근하여 django와 postgresql이 연동되어있는지 확인합니다.
user@myserver01:/home/work/ch22$ sudo docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
16e7d97d9f44 ch22-nginxtest "/docker-entrypoint.…" 3 minutes ago Up 3 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp ch22-nginxtest-1
f2d7b4b119f6 ch22-djangotest "/bin/sh -c 'gunicor…" 3 minutes ago Up 3 minutes 8000/tcp ch22-djangotest-1
user@myserver01:/home/work/ch22$ sudo docker container exec -it f2d7b4b119f6 /bin/bash
root@f2d7b4b119f6:/usr/src/app/myapp# ls
db.sqlite3 manage.py myapp
root@f2d7b4b119f6:/usr/src/app/myapp# python manage.py inspectdb
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models
root@f2d7b4b119f6:/usr/src/app/myapp# exit
exit
python manage.py inspectdb 명령어로 위와 같이 나오면 정상 실행 된 것입니다.
도커 컴포즈를 활용해 실행했던 컨테이너를 정지시킵니다.
user@myserver01:/home/work/ch22$ sudo docker compose down
[+] Running 3/3
✔ Container ch22-nginxtest-1 Removed 0.5s
✔ Container ch22-djangotest-1 Removed 10.3s
✔ Network ch22_composenet01 Removed
다음글에서는 인그레스로 웹서비스를 실행하겠습니다.
'Server' 카테고리의 다른 글
Docker & Kubernetes 개념 총 정리 8 (0) | 2025.01.17 |
---|---|
Docker & Kubernetes 개념 총 정리 7 (0) | 2025.01.16 |
Docker & Kubernetes 개념 총 정리 5 (0) | 2025.01.15 |
Docker & Kubernetes 개념 총 정리 4 (0) | 2025.01.13 |
Docker & Kubernetes 개념 총 정리 3 (0) | 2025.01.07 |
- Total
- Today
- Yesterday