공감하기
본문 바로가기
  • [!] Manual from the past has just arrived
개발일지/Django

[Django/Nginx] swagger 설정 삽질하기

by Puilin 2024. 1. 14.

gunicorn으로 wsgi 처리를 해주고 nginx로 서버를 켜보니

http://서버주소/swagger/로 접근할 때 not found (404) 에러가 떴다.

swagger는 기본적으로 ui를 로딩할 때 정적 파일을 사용하게 되어있다.

그러나 이 정적 파일의 주소를 몰라 헤메고 있던 와중에

django는 정적 파일을 한 군데로 모아주는 명령어를 지원한 다는 것을 알게 되었다.

물론 명령어를 사용하기 전에 settings.py에서 정적 파일을 모아둘 경로를 지정해놓아야 한다.

# settings.py
import os

# .. 생략

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

# .. 생략

 

그리고 명령어를 실행한다

$ python manage.py collectstatic

 

 

static 폴더가 생긴 것을 알 수 있다.

이제 nginx 설정을 만져보자

server {
        listen 80;
        server_name 서버주소;

        location / {
                include proxy_params;
                proxy_pass http://unix:/tmp/gunicorn.sock;
        }

        location /static/ {
                alias /home/ubuntu/프로젝트폴더/static/;
        }
}

 

 

위와 같이 설정하면 swagger에 접속할 때 UI들을 잘 로딩할 것이다.

하지만 여전히 not found (404) 에러가 떴다.

원인 확인을 위해 nginx의 로그를 살펴보기로 했다.

nginx의 로그는 /var/log/nginx/error.log 에서 확인 가능하다.

$ sudo tail -f /var/log/nginx/error.log

 

error.log

 

(13: Permission denied) 에러가 뜨는 것을 확인했다.

static 파일을 접근 시도하는 데까진 성공했으나 실제로 접근 권한이 없어서 일어난 일인 것 같다.

/etc/nginx/nginx.conf  파일에 정의되어 있는 user를 static 디렉터리의 소유자와 일치 시키면 될 것 같다

nginx.conf

나의 경우 amazon lightsail에서 사용하는 서버의 user 이름이 ubuntu로 되어 있다.

따라서 ubuntu로 user 이름을 일치시켜 주었다.

 

보통 이 과정을 다 거치고 나면 swagger ui가 정상적으로 뜨게 된다.

하지만 나의 경우는 삽질을 하다가 발견한 한 가지가 있는데,

혹시 위 과정을 겪고도 해결이 안 됐던 사람들을 위해 여기에 적어보려 한다.

# urls.py

# ... 생략

urlpatterns = [
    path(r'swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
    path(r'swagger', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    path(r'redoc', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc-v1'),
    path('admin/', admin.site.urls),

    path('', include('gameplay.urls')),
]

# ... 생략

 

urls.py 에서 url 패턴이 혹시 raw string(r' ')을 사용해서 코딩되어 있는지 체크해보길 바란다

swagger ui와 비슷하게 정적 파일을 사용하는 admin 페이지는 정상적으로 뜨는 것을 확인했는데,

swagger만 404를 띄우면서 보이지 않아 위 파일을 한번 수정해보았고 마참내 swagger ui가 보였다!

필자는 아래와 같이 수정했다

# urls.py

# ... 생략

urlpatterns = [
    path(r'swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
    path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    path(r'redoc', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc-v1'),
    path('admin/', admin.site.urls),

    path('', include('gameplay.urls')),
]

# ... 생략

마참내!

 

<참고한 게시물>

1) https://velog.io/@may_soouu/nginx-swagger-ui

2) https://rnokhs.tistory.com/entry/Nginx-403-13-Permission-denied-해결하기