Broadly speaking, they don't. If a public company needs to raise money, they by and large are issuing debt (bonds) not equity (stock).
The company can always create new shares. The board can decide that it wants to create another 100,000 shares, for example, so there are a total of 1.1 million shares. If I understand your scenario, the initial 1 million shares were sold at an IPO price of $20 and the price had been bid up to $40 in subsequent trading. If so, when the new shares are created, each of the existing shares is devalued so they're each worth $36.36. The company could then sell these new 100,000 shares in the market and raise another $3.6 million. But existing investors (obviously) will get upset if you devalue their existing shares so it's generally tough to get them to approve such a move unless the company is in some serious trouble.
In day to day trading, though, the company doesn't benefit directly when the stock goes from $20 to $40. It benefits indirectly if appreciating stock lets it spend less on employee salaries because stock option grants are now more lucrative and it decreases the cost of turnover because employees have "golden handcuffs" in the form of unvested options that they're motivated to stick around to cash in on. The company also benefits to the extent that it can use its now more valuable company-owned shares to do things like acquire other companies for stock rather than for cash.