HAProxy를 이용한 로드 밸런싱 구축하기 #2 : HAProxy 설치, 세팅하기.

*필자는 Google Cloud Platform 에서 테스트&시연 하였습니다.
OS : Debian GNU/Linux 9 (stretch)
머신 유형 : f1-micro

패키지 업데이트, 설치

  • sudo apt-get update -y && sudo apt-get upgrade -y
[email protected]:~# apt-get update -y && apt-get update -y
 Get:1 http://security.debian.org stretch/updates InRelease [94.3 kB]
 Ign:2 http://deb.debian.org/debian stretch InRelease                            
 Get:3 http://deb.debian.org/debian stretch-updates InRelease [91.0 kB]          
 Get:4 http://deb.debian.org/debian stretch-backports InRelease [91.8 kB]               
 Get:5 http://packages.cloud.google.com/apt cloud-sdk-stretch InRelease [6,377 B]
 Hit:6 http://deb.debian.org/debian stretch Release                                   
 Get:7 http://packages.cloud.google.com/apt google-compute-engine-stretch-stable InRelease [3,843 B]
 Hit:8 http://packages.cloud.google.com/apt google-cloud-packages-archive-keyring-stretch InRelease
 Get:9 http://security.debian.org stretch/updates/main Sources [205 kB]
 Get:10 http://security.debian.org stretch/updates/main amd64 Packages [514 kB]
 Get:11 http://security.debian.org stretch/updates/main Translation-en [227 kB]     
 Get:12 http://deb.debian.org/debian stretch-backports/main Sources.diff/Index [27.8 kB]
 Get:13 http://deb.debian.org/debian stretch-backports/main amd64 Packages.diff/Index [27.8 kB]
 Get:14 http://deb.debian.org/debian stretch-backports/main Translation-en.diff/Index [27.8 kB]
 Get:15 http://deb.debian.org/debian stretch-backports/main Sources 2019-12-12-0813.08.pdiff [31 B]
 Get:16 http://deb.debian.org/debian stretch-backports/main Sources 2019-12-13-1416.17.pdiff [236 B]
 Get:17 http://deb.debian.org/debian stretch-backports/main Sources 2019-12-28-2016.34.pdiff [1,326 B]
 Get:18 http://deb.debian.org/debian stretch-backports/main Sources 2019-12-29-0216.57.pdiff [31 B]
 Get:19 http://deb.debian.org/debian stretch-backports/main Sources 2020-01-12-1410.57.pdiff [544 B]
 Get:20 http://deb.debian.org/debian stretch-backports/main Sources 2020-01-16-0821.17.pdiff [236 B]
 Get:21 http://deb.debian.org/debian stretch-backports/main Sources 2020-01-18-2019.06.pdiff [710 B]
 Get:22 http://deb.debian.org/debian stretch-backports/main Sources 2020-01-21-1413.42.pdiff [236 B]
 Get:23 http://deb.debian.org/debian stretch-backports/main amd64 Packages 2019-12-13-1416.17.pdiff [219 B]
 Get:24 http://deb.debian.org/debian stretch-backports/main amd64 Packages 2019-12-28-2016.34.pdiff [549 B]
 Get:25 http://deb.debian.org/debian stretch-backports/main amd64 Packages 2019-12-29-0216.57.pdiff [208 B]
 Get:26 http://deb.debian.org/debian stretch-backports/main amd64 Packages 2020-01-12-1410.57.pdiff [335 B]
 Get:22 http://deb.debian.org/debian stretch-backports/main Sources 2020-01-21-1413.42.pdiff [236 B]
 Get:27 http://deb.debian.org/debian stretch-backports/main amd64 Packages 2020-01-16-0821.17.pdiff [219 B]
 Get:28 http://deb.debian.org/debian stretch-backports/main amd64 Packages 2020-01-18-2019.06.pdiff [543 B]
 Get:29 http://deb.debian.org/debian stretch-backports/main amd64 Packages 2020-01-21-1413.42.pdiff [200 B]
 Get:30 http://deb.debian.org/debian stretch-backports/main Translation-en 2020-01-18-2019.06.pdiff [228 B]
 Get:29 http://deb.debian.org/debian stretch-backports/main amd64 Packages 2020-01-21-1413.42.pdiff [200 B]
 Get:30 http://deb.debian.org/debian stretch-backports/main Translation-en 2020-01-18-2019.06.pdiff [228 B]
 Get:31 http://packages.cloud.google.com/apt cloud-sdk-stretch/main amd64 Packages [87.2 kB]
 Get:33 http://packages.cloud.google.com/apt google-compute-engine-stretch-stable/main amd64 Packages [1,169 B]
 Fetched 1,412 kB in 1s (1,098 kB/s)                
 Reading package lists… Done
 Hit:1 http://security.debian.org stretch/updates InRelease
 Hit:2 http://packages.cloud.google.com/apt cloud-sdk-stretch InRelease
 Ign:3 http://deb.debian.org/debian stretch InRelease                                          
 Hit:4 http://packages.cloud.google.com/apt google-compute-engine-stretch-stable InRelease     
 Hit:5 http://deb.debian.org/debian stretch-updates InRelease             
 Hit:6 http://deb.debian.org/debian stretch-backports InRelease           
 Hit:7 http://deb.debian.org/debian stretch Release                       
 Hit:8 http://packages.cloud.google.com/apt google-cloud-packages-archive-keyring-stretch InRelease
 Reading package lists… Done                      
 [email protected]:~#
  • sudo apt-get install haproxy -y
 [email protected]:~# apt-get install haproxy -y
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  liblua5.3-0
Suggested packages:
  vim-haproxy haproxy-doc
The following NEW packages will be installed:
  haproxy liblua5.3-0
0 upgraded, 2 newly installed, 0 to remove and 4 not upgraded.
Need to get 1,157 kB of archives.
After this operation, 2,503 kB of additional disk space will be used.
Get:1 http://deb.debian.org/debian stretch/main amd64 liblua5.3-0 amd64 5.3.3-1 [121 kB]
Get:2 http://deb.debian.org/debian stretch/main amd64 haproxy amd64 1.7.5-2 [1,036 kB]
Fetched 1,157 kB in 0s (6,224 kB/s)
Selecting previously unselected package liblua5.3-0:amd64.
(Reading database ... 37691 files and directories currently installed.)
Preparing to unpack .../liblua5.3-0_5.3.3-1_amd64.deb ...
Unpacking liblua5.3-0:amd64 (5.3.3-1) ...
Selecting previously unselected package haproxy.
Preparing to unpack .../haproxy_1.7.5-2_amd64.deb ...
Unpacking haproxy (1.7.5-2) ...
Processing triggers for libc-bin (2.24-11+deb9u4) ...
Processing triggers for systemd (232-25+deb9u12) ...
Processing triggers for man-db (2.7.6.1-2) ...
Setting up liblua5.3-0:amd64 (5.3.3-1) ...
Processing triggers for rsyslog (8.24.0-1) ...
Setting up haproxy (1.7.5-2) ...
Created symlink /etc/systemd/system/multi-user.target.wants/haproxy.service → /lib/systemd/system/haproxy.service.
Processing triggers for libc-bin (2.24-11+deb9u4) ...
Processing triggers for systemd (232-25+deb9u12) ...
Processing triggers for rsyslog (8.24.0-1) ...
[email protected]:~# 

HAProxy를 설정하기에 앞서, 각 서버의 index.html을 수정하겠습니다.

  • sudo cd /var/www/html
  • sudo nano

각 서버마다 원하는 출력 내용을 입력후
(전 Server-01 Hi! 라고 적었습니다)
Ctrl+X

Y 누르기

파일 이름 입력
index.html 입력후 *Enter*

[“index.html”파일이 이미 존재합니다. 덮어쓰시겠습니까?]
Y 를 눌러 저장을 마치시면 됩니다.

이 작업을 서버마다 반복하시면 됩니다.


기본 설정 파일 확인

  • sudo nano /etc/haproxy/haproxy.cfg
 global # 전역 변수 (전체 기본 설정)
        log /dev/log    local0 
        log /dev/log    local1 notice
        chroot /var/lib/haproxy
        stats socket /run/haproxy/admin.sock mode 660 level admin
        stats timeout 30s 
        user haproxy
        group haproxy
        daemon

        # Default SSL material locations
        ca-base /etc/ssl/certs
        crt-base /etc/ssl/private

        # Default ciphers to use on SSL-enabled listening sockets.
        # For more information, see ciphers(1SSL). This list is from:
        #  https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
        # An alternative list with additional directives can be obtained from
        #  https://mozilla.github.io/server-side-tls/ssl-config-generator/?server=haproxy
        ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES$
        ssl-default-bind-options no-sslv3

defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        timeout connect 5000 # 최대 연결 시간
        timeout client  50000 # 클라이언트 최대 연결 시간
        timeout server  50000 # 원본 서버 최대 연결 시간
        errorfile 400 /etc/haproxy/errors/400.http #400 오류 페이지
        errorfile 403 /etc/haproxy/errors/403.http #403 오류 페이지 
        errorfile 408 /etc/haproxy/errors/408.http #408 오류 페이지 
        errorfile 500 /etc/haproxy/errors/500.http #500 오류 페이지 
        errorfile 502 /etc/haproxy/errors/502.http #502 오류 페이지 
        errorfile 503 /etc/haproxy/errors/503.http #503 오류 페이지 
        errorfile 504 /etc/haproxy/errors/504.http #504 오류 페이지 

설정 파일이 정상적으로 있는것을 확인했습니다!
저희는 이 윗부분은 건들진 않고, 이 밑부분부터 이어서 작성할겁니다.


HAProxy 설정 구조

우선, Haproxy에서는 Frontend와 Backend로 나뉘어있습니다.
이 둘의 차이는 무엇일까요?

  • Frontend: 클라이언트와 HAProxy 서버 간의 연결 설정 입니다.
  • Backend: HAProxy와 실제 서버 간의 연결 설정입니다.

*주의: HAProxy는 들여쓰기(Tab)으로 Frontend, Backend를 구분합니다.
들여쓰기가 제대로 되어있지 않을경우 오류가 발생합니다.

우선 Frontend 부터 작성하겠습니다.

frontend http_front # Frontend 이름
         maxconn 10000000 # 최대 연결수 설정
         bind *:80 # 포트 설정
         stats uri /status # (옵션) 상태 페이지 주소
         stats refresh 5s # (옵션) 상태 페이지 자동 새로고침 시간
         stats hide-version #  (옵션) 상태 페이지 HAProxy 버전 숨기기
         default_backend http_backend #기본 backend 설정

그 다음은 Backend 설정을 작성하겠습니다.

backend http_backend # Backend 이름
           fullconn 100000 #최대 연결수 설정
           balance roundrobin # 알고리즘 설정
           
           server Server-01 10.128.0.3 check port 80 #Server-01 아이피 상태체크 포트 80
           server Server-02 10.128.0.4 check port 80 #Server-02 아이피 상태체크 포트 80

최종 haproxy.cfg 파일의 내용입니다.

  global # 전역 변수 (전체 기본 설정)
        log /dev/log    local0 
        log /dev/log    local1 notice
        chroot /var/lib/haproxy
        stats socket /run/haproxy/admin.sock mode 660 level admin
        stats timeout 30s 
        user haproxy
        group haproxy
        daemon

        # Default SSL material locations
        ca-base /etc/ssl/certs
        crt-base /etc/ssl/private

        # Default ciphers to use on SSL-enabled listening sockets.
        # For more information, see ciphers(1SSL). This list is from:
        #  https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
        # An alternative list with additional directives can be obtained from
        #  https://mozilla.github.io/server-side-tls/ssl-config-generator/?server=haproxy
        ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES$
        ssl-default-bind-options no-sslv3

defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        timeout connect 5000 # 최대 연결 시간
        timeout client  50000 # 클라이언트 최대 연결 시간
        timeout server  50000 # 원본 서버 최대 연결 시간
        errorfile 400 /etc/haproxy/errors/400.http #400 오류 페이지
        errorfile 403 /etc/haproxy/errors/403.http #403 오류 페이지 
        errorfile 408 /etc/haproxy/errors/408.http #408 오류 페이지 
        errorfile 500 /etc/haproxy/errors/500.http #500 오류 페이지 
        errorfile 502 /etc/haproxy/errors/502.http #502 오류 페이지 
        errorfile 503 /etc/haproxy/errors/503.http #503 오류 페이지 
        errorfile 504 /etc/haproxy/errors/504.http #504 오류 페이지  

 frontend http_front # Frontend 이름
         maxconn 10000000 # 최대 연결수 설정
         bind *:80 # 포트 설정
         stats uri /status # (옵션) 상태 페이지 주소
         stats refresh 5s # (옵션) 상태 페이지 자동 새로고침 시간
         stats hide-version #  (옵션) 상태 페이지 HAProxy 버전 숨기기
         default_backend http_backend #기본 backend 설정 

 backend http_backend # Backend 이름
           fullconn 100000 #최대 연결수 설정
           balance roundrobin # 알고리즘 설정
           
           server Server-01 10.128.0.3 check port 80 #Server-01 아이피 상태체크 포트 80
           server Server-02 10.128.0.4 check port 80 #Server-02 아이피 상태체크 포트 80 

저장후 HAProxy 서비스를 재시작 해주시면 됩니다.

  • sudo service haproxy restart

만약 재시작에 실패했을경우, 설정파일이 올바른지 다시한번 확인해보세요 🙁


결과 확인

로드밸런서 IP로 들어가보면…

만세! 작동한다!

로드밸런서가 성공적으로 작동하는걸 확인할수 있습니다!

라운드로빈 알고리즘에 의해 새로고침할때마다 서버가 번갈아가며 연결됩니다.

상태 페이지도 잘 접속되는것을 보실수 있습니다.


글을 마치며..

먼길 오시느라 수고 많으셨습니다.
여기까지는 HAProxy 로드밸런싱을 위한 기본적인 내용을 다뤘습니다.
앞으로의 글은 HAProxy에 대한 추가적인 기능들을 다룰 예정입니다.

다음은 HAProxy에서 Letsencrypt를 이용해 HTTPS를 적용하는법에 대해서 글을 올리겠습니다.

다시보는 그날까지, 안녕히계세요!

“HAProxy를 이용한 로드 밸런싱 구축하기 #2 : HAProxy 설치, 세팅하기.”의 120개의 생각

  1. Greate article. Keep writing such kind of information on your site.

    Im really impressed by your site.
    Hi there, You have done a great job. I will certainly digg it and in my view suggest to my friends.

    I’m sure they will be benefited from this web site.

    Here is my webpage: US Magazine

  2. Woah! I’m really loving the template/theme of
    this blog. It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance” between superb usability and visual appeal.
    I must say you’ve done a excellent job with this. In addition, the blog loads very quick for me on Internet
    explorer. Outstanding Blog!

    my site: delta 8 THC gummies

  3. Hiya! I know this is kinda off topic nevertheless I’d figured I’d ask.
    Would you be interested in trading links or maybe guest writing a blog post or vice-versa?
    My website discusses a lot of the same subjects as yours and I feel we could greatly benefit
    from each other. If you happen to be interested feel free to send me an email.
    I look forward to hearing from you! Excellent blog by the way!

    Stop by my web-site … weed gummies

  4. I think this is among the most significant information for me.
    And i am glad reading your article. But wanna remark on some general things, The website style is wonderful, the articles is really great :
    D. Good job, cheers

    Check out my web page: THC Gummies

  5. I’d like to thank you for the efforts you’ve put in writing this blog.
    I really hope to view the same high-grade blog posts from
    you in the future as well. In truth, your creative writing
    abilities has inspired me to get my own, personal website now 😉

    my webpage; cannibinoid oil

  6. This is the right webpage for everyone who hopes to find
    out about this topic. You understand so much its almost
    tough to argue with you (not that I really would want to…HaHa).

    You definitely put a brand new spin on a topic that’s been discussed for decades.
    Great stuff, just great!

  7. With havin so much content and articles do you ever run into any
    problems of plagorism or copyright violation? My site has a lot of unique
    content I’ve either authored myself or outsourced but it appears a lot of
    it is popping it up all over the web without my permission. Do you know any techniques to help stop content from being stolen? I’d really appreciate it.

    Feel free to surf to my site – best kratom

  8. [url=https://radio-onlayn.com.ua/]ЭВАКУАТОР[/url]

    Одна з найнеприємніших ситуацій в дорозі: поломка автомобіля. Часто це відбувається в невідповідний момент, десь в глушині, издали від майстерні. На початку водій марно намагається його перезапустити, потім намагається штовхнути і нарешті в господиніці розуміє, що доведеться замовляти евакуатор. Замість того щоб самостійно инструментізовувати трудомісткий процес транспортування в такої надзвичайної ситуації, краще довірити вирішення проблем фірмі, що здійснює технічне обслуговування і допомогу. Тому телефонний комната компанії, яка надає послуги з евакуації транспортного засобу потрібно в дорозі завжди мати під рукою дешево.
    ЭВАКУАТОР

  9. Hello there! I could have sworn I’ve been to your blog before but after going through many of the posts I realized it’s new to me.

    Anyways, I’m certainly pleased I came across it
    and I’ll be book-marking it and checking back frequently!

  10. Hey there just wanted to give you a quick heads up. The text
    in your content seem to be running off the screen in Internet explorer.
    I’m not sure if this is a format issue or something to do with browser compatibility but I figured I’d post to let you know.

    The design look great though! Hope you get the issue fixed soon. Many thanks

  11. I truly love your website.. Very nice colors & theme. Did
    you build this web site yourself? Please reply back as I’m attempting to create my own site and
    want to learn where you got this from or exactly what the theme is named.
    Many thanks!

  12. Usually I do not read post on blogs, however I would like to say that this write-up very pressured me to check out and do so!
    Your writing taste has been amazed me. Thanks, quite great post.

  13. With havin so much content and articles do you ever run into any
    issues of plagorism or copyright violation? My
    blog has a lot of unique content I’ve either created myself or outsourced but it looks like a lot
    of it is popping it up all over the internet without
    my authorization. Do you know any techniques to help protect against content from being ripped off?
    I’d truly appreciate it.

  14. I’m now not positive the place you’re getting your information, however good topic.

    I must spend some time learning more or figuring out more.
    Thank you for excellent info I used to be in search of
    this information for my mission.

  15. Hello there, I do believe your blog could possibly be having browser compatibility problems.

    When I look at your blog in Safari, it looks fine however, when opening in Internet Explorer, it’s got some overlapping issues.
    I merely wanted to provide you with a quick heads up!
    Other than that, excellent blog!

  16. Admiring the dedication you put into your website and in depth information you
    offer. It’s awesome to come across a blog every once in a while that isn’t the same out
    of date rehashed information. Great read! I’ve bookmarked your site and I’m including your
    RSS feeds to my Google account.

  17. I don’t know if it’s just me or if perhaps everyone else experiencing
    issues with your site. It seems like some of the written text within your posts are
    running off the screen. Can someone else please comment and let me know if this is
    happening to them too? This might be a problem with my
    internet browser because I’ve had this happen previously.
    Many thanks

  18. Does your site have a contact page? I’m having trouble locating it but, I’d like to
    send you an email. I’ve got some ideas for your blog you might be interested in hearing.
    Either way, great website and I look forward to seeing it grow over
    time.

  19. Hello, i think that i saw you visited my weblog thus i came
    to “return the favor”.I’m attempting to find things to enhance my site!I
    suppose its ok to use a few of your ideas!!

  20. Good day! I just wish to give you a big thumbs
    up for the excellent information you have got right here on this post.
    I’ll be coming back to your web site for more soon.

  21. you are really a good webmaster. The site loading pace is amazing. It seems that you are doing any unique trick. In addition, The contents are masterpiece. you have done a great task on this matter!

  22. Hmm is anyone else having problems with the images on this
    blog loading? I’m trying to find out if its a problem on my
    end or if it’s the blog. Any feed-back would be greatly appreciated.

  23. I’m amazed, I have to admit. Seldom do I come across a blog that’s both educative and
    amusing, and without a doubt, you have hit the nail on the
    head. The issue is something which too few people are speaking intelligently about.
    Now i’m very happy I found this during my search for something
    concerning this.

    My web-site :: heraldnet

  24. Have you ever thought about including a little bit more than just your articles?
    I mean, what you say is fundamental and all. Nevertheless think
    of if you added some great visuals or video
    clips to give your posts more, “pop”! Your content is
    excellent but with pics and video clips, this blog could definitely be one
    of the best in its field. Terrific blog!

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다