LoginSignup
43
49

More than 5 years have passed since last update.

AWSでnginx+golangが動く環境を作る

Last updated at Posted at 2015-06-24

1. nginxの設定

・EC2インスタンス立ち上げ(Amazon linuxなど)
・立ち上げたインスタンスにSSHログイン
・yumのアップデート

$ sudo yum update

・パッケージからnginxをインストール

$ sudo yum install -y nginx

・インストール後、自動起動の設定と、nginxの起動

$ sudo chkconfig nginx on
$ sudo service nginx start

・EC2インスタンスにアクセスして起動確認
nginx-01-960x490.png
このような画面が出ていればOKです。

2. goの設定

・goのインストール

$ sudo yum install -y golang

go versionが動けば問題ないです。

$ go version
go version go1.4.2 linux/amd64

・サーバー上でgoが動くように設定(confを変更)

$ vi /etc/nginx/nginx.conf

下記部分(40行目辺り)を変更

nginx.conf
server {
    listen       80;
    server_name  hostname;

    location / {
        fastcgi_pass  127.0.0.1:9000;
        include       fastcgi_params;
    }
}

・nginxの設定再読み込み

$ sudo /etc/init.d/nginx reload

Reloading nginx:[ OK ]と出ればOKです。

3. テストコードを動かしてみる

・index.goを適当な場所に配置(今回は/var/app/currentに配置)。

$ mkdir /var/app/current/
$ vi /var/app/current/index.go
index.go
package main

import (
    "fmt"
    "net"
    "net/http"
    "net/http/fcgi"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
}

func main() {
    l, err := net.Listen("tcp", "127.0.0.1:9000")
    if err != nil {
        return
    }
    http.HandleFunc("/", handler)
    fcgi.Serve(l, nil)
}

tcpソケットでListenするだけのテストコードです。
ポート番号などNginxで設定したものとあわせてください。

・Webアプリケーションを実行する

$ go run /var/app/current/index.go

もしくは、バックエンドで動かしておく場合は

$ cd /var/app/current/
$ go build index.go
$ ./index &

実行コマンドの後に & をつけることでバックグラウンドで実行されるようになります。

・EC2インスタンスにアクセスしてみる
「Hello, World!」と表示されれば完了です!

参考・その他

「Nginx + Golang でWebアプリケーション開発を試してみた」
http://umegusa.hatenablog.jp/entry/2015/02/22/025832
「EC2(Amazon Linux)に Nginx をインストールしてBasic認証する」
http://dev.classmethod.jp/etc/amazon_linux_nginx_basic_auth/
「Go言語でhttpサーバーを立ち上げてHello Worldをする」
http://qiita.com/taizo/items/bf1ec35a65ad5f608d45

beanstalkにもgo向けに事前設定されたDockerコンテナがあるのでそちらも便利です。
http://docs.aws.amazon.com/ja_jp/elasticbeanstalk/latest/dg/create_deploy_go.html

43
49
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
43
49