504 gateway timeout using webshot on meteor.js server on digital ocean ubuntu 16.04

Im working on a app that creates reports on a collection, then on the server in iron router controller, i place this code to generate my pdf using webshot, then i send the pdf by email.

works like a charm on localhost but on server keeps telling me 504 gateway timeout

this is the code on my routes.js file

    Meteor.methods({'sendMail': sendMail});
    Router.route('generatePDF', {
      path: '/reportes/generate-pdf/:_id', // example route with _id param
      where: 'server',
      action: function() {
        // Get invoice ID parameter
        var id = this.params._id;
        var tipo = Reportes.findOne(id).tipo;
        var fecha = Reportes.findOne(id).Fechadeservicio;
        // Setting name for our generated PDF

        var fileName = fecha+"-"+tipo+"-reporte_.pdf";

        // Load NPM packages
        var webshot  = Npm.require('webshot');
        var fs       = Npm.require('fs');
        var Future   = Npm.require('fibers/future');
        var fut      = new Future();
        // Set path to your route here - Meteor.absoluteUrl() is your root url ("http://localhost:3000/")
        var url      = Meteor.absoluteUrl('reportepdf/'+id); // Meteor.absoluteUrl('path/to/your/route');
        var options = {
          renderDelay: 3000,
          paperSize: {
            format: "Letter", 
            orientation: "portrait", 
            margin: "1cm",
            phantomPath: "/usr/local/share/phantomjs-1.9.8-linux-x86_64/bin/phantomjs"
          } //papersize
        }; //options
        // Magic happens here...
        webshot(url, fileName, options, function(err) {
          if (err) {
            return console.log(err);
          } else { 
            fs.readFile(fileName, function (error,data) {
              if (error) {
                return console.log(err);
              }
              fs.unlinkSync(fileName);
              fut.return(data);
            });
          }
        });

        let pdfData = fut.wait();
        let base64String = new Buffer(pdfData).toString('base64');
        sendMail({
          to: "nubestra@gmail.com",
          from: "israel@nubestra.com",
          subject: "prueba",
          nombrepdf: fileName,
          attachment: base64String
        });
        this.response.writeHead(302, {
          'Location': "/"
        });
        this.response.end();
        //this.response.writeHead(200, {'Content-Type': 'application/pdf',"Content-Disposition": "attachment; filename=" + fileName});
        //this.response.end(fut.wait());
      }
    });

I already tried setting phantomPath manually and without it, installing phantom on the host and using the one that is installed via mup automatically, increasing render delay even for 10 seconds! what else can i do?

Do yourself a favor and stop hosting on Ubuntu.

Once I switched over to Galaxy, I punched myself so hard. Getting it to work on Ubuntu is crazy hard.

You could check the version compatibility of phantom and webshot. Compare what you have installed locally and on the server. You can make sure that your app has write permission on the location you temporarily store your file. That is just off the top of my head.

Thank you for your answers, they are very valuable
@tomsp my webshot script do not store the pdf on a temporary file
i encode my pdf to base64 and attach it to an email

            let pdfData = fut.wait();
            let base64String = new Buffer(pdfData).toString('base64');
            sendMail({
              to: "nubestra@gmail.com",
              from: "israel@nubestra.com",
              subject: "prueba",
              nombrepdf: fileName,
              attachment: base64String
            });
            this.response.writeHead(302, {
              'Location': "/"
            });
            this.response.end();

when i run in console logged to the server and connected to my docker image

root@insidedockerimage:/# phantomjs --version
1.9.8

on my mac the response of phantomjs --version is
command not found

the phantom from the server is installed by default by @zodern mup

Switched to galaxy and that didnt solve my problem, on galaxy i get
502 Bad Gateway: Registered endpoints failed to handle the request.
so the problem is not with the server but with the app and the access to phantomjs

i set up diferent accesses for phantomPath

including the ones that install_phantom.js specify where phantom will be installed

they are as follows

/usr/local/share/phantomjs
/usr/local/bin/phantomjs
/usr/bin/phantomjs

webshot readme says

the location of phantomjs. Webshot tries to use the binary provided by
the phantomjs NPM module, and falls back to ‘phantomjs’ if the module
isn’t available

I know on my mac its accesing the NPM module because i have no phantom installed, i know that because phantom version returns nothing

on the server mup install phantom by default but is using neither

New found out

webshot is actually creating some pdfs on this path on the server

/bundle/bundle/programs/server

example i have this file created

/bundle/bundle/programs/server/2017-04-11-An??lisis de vibraci??n-reporte_.pdf

so the report is created…

`            webshot(url, fileName, options, function(err) {
              if (err) {
                return console.log(err);
              } else { 
                fs.readFile(fileName, function (err,data) {
                  if (err) {
                    return console.log(err);
                  }
                  fs.unlinkSync(fileName);
                  fut.return(data);
                });
              }
            });`

fs.unlinkSync(fileName); is not deleting the temporary file

finally 504 gateway timeout is not showing on screen, my page is executing the script and producing a .pdf file, what did i do?

Meteor.startup(function () {
	UploadServer.init({
    	tmpDir: process.env.PWD + '/tmp',
    	uploadDir: process.env.PWD + '/tmp/'
  	});
  	if (Meteor.isCordova) 
  	{
    	Uploader.uploadUrl = Meteor.absoluteUrl("/tmp/"); // Cordova needs absolute URL
  	}
});

Changed uploadDir and tmpDir to /tmp

also set this option on my phantom options object

            var options = {
              "phantomPath": "/usr/bin/phantomjs",
              renderDelay: 3400,
              "paperSize": {
                "format": "Letter",
                "orientation": "portrait",
                "margin": "10"
              },
              siteType: 'url',
              phantomConfig: {
                "ignore-ssl-errors": "true",
                "ssl-protocol": "any",
                "local-storage-path": "/tmp"
              }
            };

i hope i can save someone from the days (weeks) it took me to solve this