IK.AM

@making's tech note


C言語で書かれたWebアプリをCloud Foundryにデプロイする

🗃 {Dev/PaaS/CloudFoundry}
🏷 Cloud Foundry 🏷 Docker 🏷 C 
🗓 Updated at 2017-01-25T13:56:14Z  🗓 Created at 2017-01-25T13:49:17Z   🌎 English Page

訳あってC言語で書かれたWebアプリをCloud FoundryにデプロイしたいときのTips。

次の簡易HTTPサーバー(~/work/httpserver/httpserver.c)をデプロイしてみる。

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main()
{
  int sock0;
  struct sockaddr_in addr;
  struct sockaddr_in client;
  unsigned len;
  int sock;
  int yes = 1;

  char buf[2048];
  char inbuf[2048];

  sock0 = socket(AF_INET, SOCK_STREAM, 0);
  if (sock0 < 0) {
    perror("socket");
    return 1;
  }

  addr.sin_family = AF_INET;
  addr.sin_port = htons(8080);
  addr.sin_addr.s_addr = INADDR_ANY;

  setsockopt(sock0, SOL_SOCKET, SO_REUSEADDR, (const char *)&yes, sizeof(yes));
  if (bind(sock0, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
    perror("bind");
    return 1;
  }
  if (listen(sock0, 5) != 0) {
    perror("listen");
    return 1;
  }

  memset(buf, 0, sizeof(buf));
  snprintf(buf, sizeof(buf),
       "HTTP/1.1 200 OK¥r¥n"
       "Content-Length: 14¥r¥n"
       "Content-Type: text/html¥r¥n"
       "¥r¥n"
       "Hello World!¥r¥n");
  
  while (1) {
    len = sizeof(client);
    sock = accept(sock0, (struct sockaddr *)&client, &len);
    if (sock < 0) {
      perror("accept");
      break;
    }
    memset(inbuf, 0, sizeof(inbuf));
    recv(sock, inbuf, sizeof(inbuf), 0);
    // printf("%s", inbuf); // for debug
    send(sock, buf, (int)strlen(buf), 0);
    close(sock);
  }

  close(sock0);

  return 0;
}

HTTPサーバーはGeekなぺーじの例を使用した。

Cloud Foundryのrootfsであるcflinux2でこのコードをコンパイルする。cflinux2のDockerイメージを使用する。

$ docker run -v ~/work/httpserver:/tmp cloudfoundry/cflinuxfs2 gcc /tmp/httpserver.c -o /tmp/httpserver

手元にhttpserverができている。

$ ls -lh ~/work/httpserver
total 32
-rwxr-xr-x  1 makit  wheel   8.9K Jan 25 22:28 httpserver
-rw-r--r--  1 makit  wheel   1.3K Jan 25 22:27 httpserver.c

これをBinay Buildpackを使ってデプロイする。メモリは少量でOK。

$ cf push http-server -c './httpserver' -b binary_buildpack -m 8m
...
App started


OK

App http-server was started using this command `./httpserver`

Showing health and status for app http-server in org foo / space staging as xxxxx@gmail.com...
OK

requested state: started
instances: 1/1
usage: 8M x 1 instances
urls: http-server.cfapps.io
last uploaded: Wed Jan 25 13:29:23 UTC 2017
stack: cflinuxfs2
buildpack: binary_buildpack

     state     since                    cpu    memory       disk         details
#0   running   2017-01-25 10:29:47 PM   0.0%   2.5M of 8M   1.3M of 1G

普通に動く。

image

manifest.ymlを使う場合は次のような内容にする。

---
applications:
- name: http-server
  buildpack: binary_buildpack
  memory: 8m
  command: ./httpserver

あとは

$ cf push

✒️️ Edit  ⏰ History  🗑 Delete