Amazon.com Inc. is best known for transforming the U.S. retail industry, a feat that President Donald Trump has recently attacked.

But the company has quietly been cultivating a major customer in his own backyard: the federal government.

In the past several years, the Seattle-based company has won much of the business to help the government...