These errors can be thrown during publication if nginx server is used for builder. Usually the reason of them is script timeout. Increase timeout for nginx script execution (parameter fastcgi_read_timeout), restart nginx server and check if error is gone.
If nginx server is used as proxy server for Apache then increasing these parameters in nginx configuration may help to solve the problem:
proxy_connect_timeout,
proxy_send_timeout,
proxy_read_timeout,
send_timeout