如果后端离线,则不提供静态文件

时间:2018-12-07 10:01:03

标签: rest nginx webserver

我有以下nginx配置,用于处理为我的静态网站提供服务并将请求重定向到我的REST后端:

net = Net(20, 20, 20, nb_lstm_layers)
optimizer = optim.Adam(net.parameters(), lr=0.0001, weight_decay=0.0001)
criterion = nn.MSELoss()

for epoch in range(nb_epoch):
    count = 0
    loss_sum = 0

    batch_x = None
    for i in (range(len(data))): 
    # data is my entire data, which contain A and B i specify above.
        temp_x = torch.tensor(data[i][0])
        temp_y = torch.tensor(data[i][1])

        for ii in range(0, data[i][0].shape[0] - nb_frame_in_batch*2 + 1): # Create batches 
            batch_x, batch_y = get_batches(temp_x, temp_y, ii, batch_size, nb_frame_in_batch)  
            # this will return 2 tensor of shape (batch_size, nb_frame_in_batch, 20), 
            # with `batch_size` is the number of sample each time I feed to the net, 
            # nb_frame_in_batch is the number of frame in each sample
            optimizer.zero_grad()

            h_state = net.hidden_init()

            prediction, h_state = net(batch_x.float(), h_state)
            loss = criterion(prediction.float(), batch_y.float())

            h_state = (h_state[0].detach(), h_state[1].detach())

            loss.backward()
            optimizer.step()

如果我的REST后端脱机,则proxy module返回HTTP状态“ 502 Bad Gateway”,我可以通过添加以下内容将请求重定向到状态页:

server {
    listen 80 default_server;
    server_name _;

    # Host static content directly
    location / {
        root /var/www/html;
        index index.html;
        try_files $uri $uri/ =404;
    }

    # Forward api requests to REST server
    location /api {
        proxy_pass http://127.0.0.1:8080;
    }

}

但是,这仅适用于直接访问REST后端的请求。后端离线时,如何以相同的方式将请求重定向到我的静态网站?

2 个答案:

答案 0 :(得分:4)

Nginx确实具有一些health check和状态监视功能,这些功能似乎可以相互关联,但是我找不到使用它们的正确方法。

虽然其预期的用例实际上是用于授权的,但我发现nginx的auth_request模块对我有用:

# Host static content directly
location / {
    # Check if REST server is online before serving site
    auth_request /api/status; # Continues when 2xx HTTP status is returned
    # If not, redirect to offline status page
    error_page 500 =503 @status_offline;

    root /var/www/html;
    index index.html;
    try_files $uri $uri/ =404;
}

在提供静态内容之前,它将作为子请求调用/api/status,并且仅在子请求返回200范围内的HTTP状态时才继续。服务器离线时,似乎返回状态500。

此方法可能会对性能产生影响,因为您现在总是在做一个额外的请求,但这似乎是检查服务是否在线的内在要求。

答案 1 :(得分:0)

我认为这是正确的答案-auth请求非常适合您想要在返回请求的内容之前“ ping”后端的任何情况。

过去,我曾对nginx服务器使用过类似的方案,在该服务器上,我想在代理S3存储桶之前检查auth标头是否正确。